Redux 实际上是一个数据层框架,它将数据存储在Store 中。每个组件可以从Store 中获取数据,也可以修改Store 中的数据。
Redux 的工作流程 Redux Flow
如下,请求Store数据:React Components 向 Action Creators 发送请求获取Store 中的数据,Action Creators 向Store 提交请求,Store 则向Reducers 请求查询这个数据,Reducers 告知Store 这个数据的值,然后Store 向React Components 返回结果。
同理,修改Store数据:React Components 向 Action Creators 发送请求修改Store 中的数据,Action Creators 向Store 提交修改请求,Store 则向Reducers 请求如何修改,Reducers 告知Store 如何修改数据的值,然后Store 修改这个数据,改完后Store会告知React Components 修改完成可以重新获取数据了。
创建 redux 中的 store
首先我们需要安装redux
使用命令: yarn add redux
安装好后。我们在项目的src 目录下,创建一个目录 名叫store。在store 目录下,创建一个文件 index.js 。
这个index.js 就是创建 store 代码存放的位置了。
下面就是这个index.js 的代码,创建了一个store 。
import { createStore } from 'redux';
const store = createStore();
export default store;
如前所述,仅仅有store 是没用的,还得有 reducers 。
因此,我们在src/store 目录下,再创建一个文件reducer.js 。
reducer.js 代码只需要返回一个函数就可以了。代码如下,其中 匿名函数中的 state 指整个 store 中存储的数据。
好了,已经创建好 reducer了。
const defaultState = {};
export default (state = defaultState, action) => {
return state;
}
下面,我们把reducer 传递给store。在 src/store/index.js 中引入,如下。
import { createStore } from 'redux';
import reducer from './reducer';
const store = createStore(reducer);
export default store;
好啦。现在我们开始使用了。
先在reducer.js 中添加两项数据,如下。
const defaultState = {
inputValue: '',
list: []
};
export default (state = defaultState, action) => {
return state;
}
下面,我们的组件就可以连接 store 获取数据了。
这是我们之前写死数据的组件,BeautifulToDoList。
import React, {Component} from 'react';
import 'antd/dist/antd.css';
import { Input, Button, List } from 'antd';
const data = [
'Racing car sprays burning fuel into crowd.',
'Japanese princess to wed commoner.',
'Australian walks 100km after outback crash.',
'Man charged over missing wedding girl.',
'Los Angeles battles huge wildfires.',
];
class BeautifulToDoList extends Component {
render() {
return (
<div style={{marginTop: '10px',marginLeft: '10px'}}>
<Input
placeholder="todo info"
style={{width: 300, marginRight: '10px'}}
/>
<Button type="primary">提交</Button>
<List
style={{marginTop: '10px', width: '300px'}}
bordered
dataSource={data}
renderItem={item => (<List.Item>{item}</List.Item>)}
/>
</div>
)
}
}
export default BeautifulToDoList;
现在,我们将<List> 中的数据换为 store 中的数据。
import React, {Component} from 'react';
import 'antd/dist/antd.css';
import { Input, Button, List } from 'antd';
import store from './store/index.js';
class BeautifulToDoList extends Component {
constructor(props) {
super(props);
console.log(store.getState());
this.state = store.getState();
}
render() {
return (
<div style={{marginTop: '10px',marginLeft: '10px'}}>
<Input
value={this.state.inputValue}
placeholder="todo info"
style={{width: 300, marginRight: '10px'}}
/>
<Button type="primary">提交</Button>
<List
style={{marginTop: '10px', width: '300px'}}
bordered
dataSource={this.state.list}
renderItem={item => (<List.Item>{item}</List.Item>)}
/>
</div>
)
}
}
export default BeautifulToDoList;