使用React-redux
什么是react-redux
- 第三方模块,可以帮助我们在react中更方便的使用redux。
安装
- 安装 redux
npm install redux
- 安装 react-redux
npm install react-redux
代码示例
| 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,Provider内所有的组件都可以获取到store的数据。
<Provider store={store}>
<TodoList />
</Provider>
)
ReactDOM.render(APP, document.getElementById('root'))
|
| import React from "react";
import { connect } from "react-redux";
const TodoList = (props) => {
const { inputValue, list, changeInputValue, handleClick, handleDelete } = props;
return (
<div>
<div>
<input value={inputValue} onChange={changeInputValue}/>
<button onClick={handleClick}>提交</button>
</div>
<ul>
{
list.map((item, index) => {
return <li onClick={() => {handleDelete(index)}} key={index}>{item}</li>
})
}
</ul>
</div>
)
}
// 把组件里的state映射到props,其中state就是store里的数据。
const mapStateToProps = (state) => {
return {
inputValue: state.inputValue,
list: state.list
}
}
// store.dispatch挂载到props上
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(index) {
const action = {
type: 'del_item',
index: index
}
dispatch(action)
}
}
}
// 让todolist与store连接,connect就是连接的意思,连接规则在 ↑ mapStateToProps中
export default connect(mapStateToProps, mapDispatchToProps)(TodoList);
|
| import {createStore} from 'redux'
import reducer from './reducer'
const store = createStore(reducer);
export default store;
|
| 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;
}
if (action.type === 'del_item') {
const newState = JSON.parse(JSON.stringify(state))
newState.list.splice(action.index, 1);
return newState;
}
return state;
}
|