redux不同与vuex,需要异步的话,需要用到thunk
1、创建需要用到的文件
第一步:src路径下创建目录文件 store,store下创建 index.js (用于创建store数据仓库),reducer.js(用于单独存储数据),actionTypes.js(用于存放action方法的type),actionCreators.js(用于存放action方法)、thunk.js(用于存放异步操作)
安装依赖:npm i redux
npm i redux-thunk // 异步
2、index.js
// 解构出 createStore()
import { createStore, applyMiddleware } from 'redux'
// 引入thunk
import thunk from 'redux-thunk';
// 引入reducer
import state from './reducer'
// 创建store数据仓库
let store = createStore(state, applyMiddleware(thunk))
export default store;
3、reducer.js
// 引入actionTypes
import { SET_STATE_MSG } from './actionTypes';
// state属性
const defaultState = {
msg: '旧数据'
}
// 导出
export default (state = defaultState, actions) => {
// set_State更改msg数据的方法
if (actions.type == SET_STATE_MSG) {
state.msg = actions.value
}
return state
}
4、actionTypes.js
// 更改msg数据的type标识
export const SET_STATE_MSG = 'set_state_msg'
5、actionCreators.js
// 更改msg数据的type标识
import { SET_STATE_MSG } from './actionTypes';
export let set_state_action = (value) => {
return {
type: SET_STATE_MSG,
value
}
}
6、thunk.js
// 引入actionCreators
import { set_state_action } from './actionCreators';
// 使用 thunk【异步】
export const set_state_actionThunk = () => {
return dispatch => {
// 可以发送 axios 请求
let data = '异步数据'
dispatch(set_state_action(data))
}
}
使用
import React, { Component } from 'react';
import './index.css'
// 引入store
import store from '../../store';
// 如果是同步 引入actionCreators 如果有异步需求 引入thunk.js 注意下边点击按钮时方法的名字要
// import { set_state_action } from '../../store/actionCreators';
import { set_state_actionThunk } from '../../store/thunk';
class index extends Component {
state = { }
// 构造器
constructor() {
super();
store.subscribe(this.set_state_action_add)
}
// 设置store中的state到组件中的state
set_state_action_add = () => {
this.setState({
name: '1'
})
}
render() {
return (
<div>
<h2>state数据:{store.getState().msg}</h2>
<button onClick={() => store.dispatch(set_state_actionThunk())}> 改变state数据</button>
</div >
);
}
}
export default index