React-Redux-综合运用(在React中使用)
  TEZNKK3IfmPf 2023年11月14日 24 0

在之前的 ​​React-Redux-优化​​ 文章当中说明了一个问题需要解决,在本文主要介绍的就是这个问题的解决方案;

  • store、action、reducer 代码都写在一个文件中,不利于维护

这个问题呢,可以在项目工程当中新建一个 store 文件夹,在该文件夹当中分别创建 ​​action.js​​​,​​constants.js​​​,​​reducer.js​​​,​​store.js​​ 等文件:

  • action.js
import {
ADD_COUNT,
SUB_COUNT
} from './constants';

// 利用action来修改状态
export const addAction = (num) => {
return {type: ADD_COUNT, num: num};
};
export const subAction = (num) => {
return {type: SUB_COUNT, num: num};
};
  • constants.js
export const ADD_COUNT = 'ADD_COUNT';
export const SUB_COUNT = 'SUB_COUNT';
  • reducer.js
import {
ADD_COUNT,
SUB_COUNT
} from './constants';

// 定义一个状态
let initialState = {
count: 666
};

// 利用reducer将store和action串联起来
function reducer(state = initialState, action) {
switch (action.type) {
case ADD_COUNT:
return {count: state.count + action.num};
case SUB_COUNT:
return {count: state.count - action.num};
default:
return state;
}
}

export default reducer;
  • store.js
import {createStore} from 'redux';
import reducer from './reducer';

// 利用store来保存状态(state)
const store = createStore(reducer);

export default store;
  • App.js
import React from 'react';
import store from './store/store';
import {addAction, subAction} from './store/action';

class App extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
count: store.getState().count
}
}

componentDidMount() {
store.subscribe(() => {
this.setState({
count: store.getState().count
})
})
}

componentWillUnmount() {
store.unsubscribe();
}

render() {
return (
<div>
<p>{this.state.count}</p>
<button onClick={() => {
this.btnClick()
}}>
增加
</button>
</div>
)
}

btnClick() {
store.dispatch(addAction(5));
}
}

export default App;
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2023年11月15日   33   0   0 reactjavascript
  TEZNKK3IfmPf   2023年11月14日   18   0   0 reactRedux
  TEZNKK3IfmPf   2023年11月14日   23   0   0 react
  TEZNKK3IfmPf   2023年11月14日   17   0   0 react函数
  TEZNKK3IfmPf   2023年11月14日   28   0   0 react
  TEZNKK3IfmPf   2023年11月14日   28   0   0 react继承
  TEZNKK3IfmPf   2023年11月14日   19   0   0 react编程开发
  TEZNKK3IfmPf   2023年11月14日   21   0   0 react编程开发
  TEZNKK3IfmPf   2023年11月14日   22   0   0 react编程开发
  TEZNKK3IfmPf   2023年11月14日   24   0   0 react编程开发
  TEZNKK3IfmPf   2023年11月14日   26   0   0 react
  TEZNKK3IfmPf   2023年11月14日   37   0   0 react
  TEZNKK3IfmPf   2024年03月22日   71   0   0 htmlreact
  TEZNKK3IfmPf   2023年11月15日   36   0   0 react
  TEZNKK3IfmPf   2023年11月14日   33   0   0 react
TEZNKK3IfmPf