React-Redux使用方法
理解
在React项目中使用react-redux,可以让你更方便的使用redux,原理是在index.js
中注册app时用一个<Povider>
标签嵌套,把你的App.js变Provideer
的子组件,将所有的state
以props
的形式传给<App/>
。
代码
App.js
/*
* @Author: YooHoeh
* @Date: 2018-07-17 09:42:21
* @Last Modified by: YooHoeh
* @Last Modified time: 2018-07-17 15:11:30
* @Description:
*/
import React, { Component } from "react";
import { connect } from "react-redux";
import { deletItem, addItem, inputValueChange } from "./store/actionCreator";
const TodoList = props => {
const { inputValue, handleInputChange, handleClick, handleDelItem } = props;
return (
<div>
<div>
<input value={inputValue} onChange={handleInputChange} />
<button onClick={handleClick}>Submit</button>
</div>
<ul>
{props.list.map((item, index) => {
return (
<li key={index} onClick={() => handleDelItem(index)}>
{item}{" "}
</li>
);
})}
</ul>
</div>
);
};
const mapStateToProps = state => {
return {
inputValue: state.inputValue,
list: state.list
};
};
const mapDispatchToProps = dispatch => {
return {
handleInputChange(e) {
const action = inputValueChange(e.target.value);
dispatch(action);
},
handleClick() {
const action = addItem();
dispatch(action);
},
handleDelItem(index) {
const action = deletItem(index);
dispatch(action);
}
};
};
// 导出connect方法将Todolis和store做连接
// 原理是ProVider将state和dispatch以props的方式传给Todolist
// 将UI组件连接成容器组件
export default connect(
mapStateToProps,
mapDispatchToProps
)(TodoList);
index.js
/*
* @Author: YooHoeh
* @Date: 2018-07-17 09:53:55
* @Last Modified by: YooHoeh
* @Last Modified time: 2018-07-17 10:23:50
* @Description:
*/
import React from "react";
import ReactDOM from "react-dom";
import TodoList from "./TodoList";
import { Provider } from "react-redux";
import store from "./store";
const App = (
<Provider store={store}>
{/*这样的话里面的所有组件都可以获取Store里面的state了*/}
<TodoList />
</Provider>
);
ReactDOM.render(App, document.getElementById("root"));