react-redux
帮助我们在react中方便使用redux
在src目录下只有一个index.js的js文件
首先安装它
创建TodoList.js
src下创建文件夹store
store下创建index.js
store下创建reducer.js
reducer.js
const defaultState ={
inputValue :' ',
list: []}
export default (state=defaultState,action) =>{
if(action.type === 'change_input_value') {
const newState =JSON.parse(JSON.stringify(state));
newState.inputValue =action.value;
return newState;}
if(action.type === 'add_item') {
const newState =JSON.parse(JSON.stringify(state));
newState.list.push(newState.inputValue);
newState.inputValue=' ';
return newState;}
return state;
}
store/index.js
import { createStore }from 'redux';
import reducer from './reducer';
const store = createStore();
export default store;
TodoList.js
import React,{Component } from 'react';
//import store from './store';
import { connect } from 'react-redux';
class TodoList extends Component {
//constructor(props_{
//super(props);
//this.state =store.getState();
}
render(){
//const {inputValue,changeInputValue,handleClick} =this.props;
//有这一行时 this.props.inputValue就可以改成inputValue了
return (
<div>
<div>
<input value={this.props.inputValue}
onChange={this.props.ChangeInputValue}/>
//{this.state.inputValue}/>
<button
onClick {this.handleClick.bind(this)}>提交</button>
</div>
<ul>
{
this.props.list.map((item,index)=>{
return <li onClick={this.props.handleDelete} key={index}>{item}</li>
})
}
</ul>
<div>
)
}
}
const mapStateToProps = (state) => {
//把store里state里的inputValue映射到组件里的inputValue
return {
inputValue:state.inputValue,
list:state.list
}
const mapDispatchToProps =(dispatch) =>{
return {
ChangeInputValue(e){
const action ={
type:'change_input_value',
value:e.target.value
}
dispatch(action);
}
handleClick(){
const action = {
type:'add_item'
}
dispatch(action);
},
handleDelete(){
.....//同理
}
}
}
}
export default connect(mapStateToProps,mapDispatchToProps)(TodoList);
//使TodoList组件和store进行链接
//数据映射在mapStateToProps 对数据修改是mapDispatchToProps
//export default TodoList;
src/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 App =(
<Provider store={store}>
//提供器提供了store 则里面所有组件都能获取到store里的内容
<TodoList />
</Provider>//也是一个组件 react-redux的核心API
ReactDOM.render(App,document.getElementById('root'));
//ReactDOM.render(<TodoList />,document.getElementById('root'));