使用react-redux完成TodoList
react-redux实际上就是在redux的基础上进行了一些改进,原store文件夹下的内容没有发生任何改变。
主要通过使用react-redux中的提供器Provider和连接器connect进行优化
- 在使用connect连接器方法进行导出时,该方法需接收两个参数:第一个参数为状态映射函数,第二个参数为派发映射函数,传递这两个参数的目的为在组件内部可以通过props使用state和dispatch;
- 使用Provider包裹的组件可以直接通过props获取state和dispatch(前提:该组件使用connect方法进行导出),而不需要单独的导入store文件
文件目录
src/index.js入口文件
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import App from "./App";
import store from "./store";
ReactDOM.render(
<Provider store={store}>
<App/>
</Provider>,
document.getElementById("root")
);
src/App.js
import React from "react";
import TodoList from "./components/TodoList";
export default function App() {
return (
<div>
<TodoList/>
</div>
);
}
src/store/reducer.js
import { createStore } from "redux";
import reducer from "./reducer";
const store = createStore(reducer);
export default store;
src/store/index.js
const defaultState = {
inputValue: "I love watching movie",
listData: ["I love playing ow", "I love coding"],
};
export default (state = defaultState, action) => {
let newState = JSON.parse(JSON.stringify(state));
switch (action.type) {
case "update_ipt_val":
newState.inputValue = action.value;
break;
case "add_list_item":
newState.inputValue.trim().length > 0 &&
newState.listData.push(newState.inputValue);
newState.inputValue = "";
break;
case "delete_list_item":
newState.listData.splice(action.value, 1);
default:
break;
}
return newState;
};
src/components/TodoList.js
import React, { Component } from "react";
import { Input, Button, List } from "antd";
import { connect } from "react-redux";
class TodoList1 extends Component {
render() {
return (
<div>
<Input
placeholder="请输入内容"
value={this.props.inputValue}
onChange={this.props.changeHandle.bind(this)}
style={{ width: 400, margin: 15 }}
/>
<Button type="primary" onClick={this.props.clickHandle.bind(this)}>
确认
</Button>
<List
bordered
dataSource={this.props.listData}
renderItem={(item, index) => (
<List.Item
onDoubleClick={this.props.dbClickHandle.bind(this, index)}
style={{ userSelect: "none" }}
>
{item}
</List.Item>
)}
style={{ width: 400, marginLeft: 15 }}
/>
</div>
);
}
}
// 状态映射函数 通过props传递数据
const mapStateToProps = (state) => {
return {
inputValue: state.inputValue,
listData: state.listData,
};
};
// 派发映射函数 通过props调用方法
const mapDispatchToProps = (dispatch) => {
return {
clickHandle() {
const action = {
type: "add_list_item",
};
dispatch(action);
},
changeHandle(e) {
const action = {
type: "update_ipt_val",
value: e.target.value,
};
dispatch(action);
},
dbClickHandle(index) {
const action = {
type: "delete_list_item",
value: index,
};
dispatch(action);
},
};
};
export default connect(mapStateToProps, mapDispatchToProps)(TodoList1);