安装使用
1.安装依赖
react-redux
需要依赖redux
npm install redux react-redux --save
2.初始化Redux
创建src/store/index.js
文件,并编写如下内容
import {createStore} from 'redux'
import reducer from './reducer'
const store = createStore(reducer)
export default store;
创建src/store/reducer.js
文件,并编写如下内容
import { ADD_ITEM, INPUT_CHANGE, DELETE_ITEM } from './actionTypes';
const defaultState = {
keyword: '',
list: [],
};
export default (state = defaultState, action) => {
// 拷贝状态数据, reducer只能接收state,不能直接改变state,修改把备份数据,然后将新状态数据返回
let newState = JSON.parse(JSON.stringify(state));
// 改变状态
switch (action.type) {
case INPUT_CHANGE:
newState.keyword = action.value;
break;
case ADD_ITEM:
newState.list.push(newState.keyword);
newState.keyword = '';
break;
case DELETE_ITEM:
newState.list.splice(action.value, 1);
break;
}
console.log(newState);
// 返回新数据
return {
...state,
...newState,
};
};
创建src/store/actionTypes.js
文件并编写如下内容
export const ADD_ITEM = 'addItem'
export const INPUT_CHANGE = 'inputChange'
export const DELETE_ITEM = 'deleteItem'
3.使用react-redux
在入口文件src/index.js
中引入Provider,store
,并使用
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store/index';
import TodoList from './TodoList';
const App = (
);
ReactDOM.render(App, document.getElementById('root'));
4.将组价和状态进行关联,通过connect
src/TodoList/index.js
import React from 'react';
import './index.css';
import { connect } from 'react-redux';
import { ADD_ITEM, INPUT_CHANGE, DELETE_ITEM } from '../store/actionTypes';
const TodoList = (props) => {
let { inputChange, keyword, addItem, list ,deleteItem} = props;
return (
Hello ReactRedux
{list.map((item, index) => {
return (
{deleteItem(index)}}>
{item}
);
})}
);
};
// 将state映射为props
const stateToProps = (state) => {
return {
keyword: state.keyword,
list: state.list,
};
};
// 将action和prop进行关联
const dispatchToProps = (dispatch) => {
return {
inputChange(e) {
console.log(e.target.value);
dispatch({
type: INPUT_CHANGE,
value: e.target.value,
});
},
addItem() {
dispatch({
type: ADD_ITEM,
});
},
deleteItem(index) {
dispatch({
type: DELETE_ITEM,
value: index,
});
},
};
};
export default connect(stateToProps, dispatchToProps)(TodoList);
学习资料
react-redux