官方网站:https://react-redux.js.org/
项目地址:https://gitee.com/XiaoYuZhou233/React-TodoList/tree/Redux7/my-app
1.安装
用npm命令安装
npm install --save react-redux
2.项目入口文件
index.js是整个项目的入口文件,在这里开始使用
import React from 'react';
import ReactDOM from 'react-dom';
import TodoList from './TodoList';
import { Provider } from 'react-redux'
import store from './store'
const rootElement = document.getElementById('root');
//Provider连接了store,里面包裹的所有组件都能获取store内容
const App = (
<Provider store={store}>
<TodoList/>
</Provider>
);
ReactDOM.render(
App,
rootElement
);
3.使用中间件redux-thunk发送异步请求
在store下的index.js中:
//Store 的创建
import reducer from './reducer'
import { createStore, applyMiddleware,compose } from 'redux';
import thunk from 'redux-thunk';
//applyMiddleware函数:用于Redux中间件的使用,参数是中间件名,也可以用数组形式使用多个中间件
const store = createStore(
reducer,
applyMiddleware(thunk)
);
export default store;
4.连接Store
在TodoList组件中:
import React, {Fragment} from 'react';
import {getInputChangeAction,getAddItemAction,getDeleteItemAction,getInitList} from './store/actionCreators'
import {connect} from 'react-redux';
import 'antd/dist/antd.css'; // 导入样式
import {Input, Button, List} from 'antd'; // 导入组件
import TodoItem from "./TodoItem";
class TodoList extends React.Component{
render(){
return (
<Fragment>
<div style={{marginTop: '10px', marginLeft: '10px'}}>
<Input
style={{width: '300px'}}
id='insertArea'
className="input"
value={this.props.inputValue}
placeholder={'todo info'}
onChange={this.props.handleInputChange}
/>
<Button type="primary" onClick={this.props.handleBtnClick}>submit</Button>
<List
style={{marginTop: '10px', width: '300px'}}
bordered
dataSource={this.props.list}
renderItem={(item,index) =>(
<TodoItem
index={index}
delItem={this.props.handleItemDelete}
con={item}
/>
)
}
/>
</div>
</Fragment>
)
}
componentDidMount() {
this.props.initList();
}
}
//========将本组件与store做连接并导出==========
/*connect的第一个参数:把store的内容(在Reducer)中写入映射到该组件中成为组件的属性this.props*/
const mapStateToProps = (state /*, ownProps*/) => {
return { // 返回一个对象
inputValue:state.inputValue,
list:state.list
}
};
/*将store的dispatch方法挂载到该组件的this.props*/
const mapDispatchToProps=(dispatch)=>{
return {
handleInputChange(event) {
//action对象创建
const action =getInputChangeAction(event.target.value);
//把action传递给store
dispatch(action);
},
handleBtnClick() {
const action = getAddItemAction();
dispatch(action);
},
handleItemDelete(index) {
const action = getDeleteItemAction(index);
dispatch(action);
},
initList(){
const action=getInitList();
dispatch(action);
}
}
};
/*
React-Redux 规定,所有的 UI 组件都由用户提供,容器组件则是由 React-Redux 自动生成。
也就是说,用户负责视觉层,状态管理则是全部交给它。
*/
export default connect(mapStateToProps,mapDispatchToProps)(TodoList);