我所理解的redux
在我看来,redux就是将数据放到一个store的仓库里面管理,一个组件改变了store中数据的内容,其他组件感知到变化之后,然后再去取数据,间接实现数据传递的问题。
redux的工作原理
简单来说就是,react components想要一个东西,那么它就通过action Creators告诉store,然后store去reducers中查找,然后reducers再将查询到的数据返回给store,store拿到数据之后就返回给react components。
那么如何完成一个todolist的小项目呢?
首先需要安装redux,在控制台输入npm install reducer --save
然后需要创建一个store的文件夹,文件夹中有一个index.js和一个reducer.js的文件
最后在需要使用的地方引入这个store文件中的index文件就可以了import store from './store';
在需要使用store的文件中:
import React,{ Component,Fragment } from 'react';
import "antd/dist/antd.css";
import { Input,Button,List } from "antd";
import store from "./store";
class TodoList extends Component {
constructor(props){
super(props);
this.state = store.getState();
this.handleInputChange = this.handleInputChange.bind(this);
this.handleStoreChange = this.handleStoreChange.bind(this);
this.handleBtnClick = this.handleBtnClick.bind(this);
//store的数据只要改变这个函数就被自动执行
store.subscribe(this.handleStoreChange);
}
render() {
return (
<Fragment>
<Input placeholder="Basic usage" style={{width:300}} value={this.state.inputValue} onChange={this.handleInputChange}/>
<Button onClick={this.handleBtnClick}>Default</Button>
<List
style={{width:300,marginTop:20}}
bordered
dataSource={this.state.list}
renderItem={(item ,index)=> (
<List.Item onClick={this.handleDeteleItem.bind(this,index)}>
{item}
</List.Item>
)}
/>
</Fragment>
)
}
handleInputChange(e) {
//告诉store我需要更改数据
const action = {
type:'change_input_value',
value: e.target.value
}
//将数据传递给store
store.dispatch(action)
}
handleStoreChange(){
//当我感知到数据变化时,我再重新调取数据
this.setState(store.getState())
}
handleBtnClick() {
const action = {
type:'add_todo_item'
}
store.dispatch(action)
}
handleDeteleItem(index){
const action = {
type:'delete_todo_item',
index
}
alert(index)
store.dispatch(action)
}
}
export default TodoList;
在index.js中的代码如下:
import { createStore } from 'redux';
//引入reducer
import reducer from './reducer';
const store = createStore(reducer);
export default store;
在reducer.js中
const defaultState = {
inputValue:'',
list:[]
}
export default (state = defaultState,action) => {
if(action.type === 'change_input_value'){
//从原来的store里的数据,拷贝一份
const newState = JSON.parse(JSON.stringify(state));
//将原来的inputva更改成我传递过来的新的值
newState.inputValue = action.value;
//将新的数据返回出去
return newState
}
if(action.type === 'add_todo_item'){
//从原来的store里的数据,拷贝一份
const newState = JSON.parse(JSON.stringify(state));
//往新的数组里面增加inputValue
newState.list.push(newState.inputValue);
//将inputvalue设置为空
newState.inputValue = '';
//将新的数据返回出去
return newState
}
if(action.type === 'delete_todo_item'){
//从原来的store里的数据,拷贝一份
const newState = JSON.parse(JSON.stringify(state));
//往新的数组里面增加inputValue
newState.list.splice(action.index,1)
//将新的数据返回出去
return newState
}
return state;
}
这样就完整的完成了一个点击增加数据,点击删除数据的小项目了。