yarn add redux react-redux redux-devtools
redux-devtools(是调试redux的)
首先需要创建文件夹 store
store创建一个index.js
store文件index.js 内容
import { createStore } from "redux"; export default function configureStore() { const store = createStore(); return store; }
什么时候需要用到redux 只有在关联的时候 才会用到react-redux
然后 再去创建reducers文件夹
reducers文件auth.js 内容
const initState = {}; export default function auth(state = initState, action) { switch (action.type) { case "INIT_AUTH": return (state = action.data); case "UPDATE_AUTH": return (state = action.data); default: return state; } }
reducers文件index.js 内容
import { combineReducers } from "redux"; import auth from "./auth"; const rootReducers = combineReducers({ auth }); export default rootReducers;
然后再去创建actions文件夹
action文件auth.js 内容
export function initAuth(data) { return { type: "INIT_AUTH", data }; } export function updateAuth(data) { return { type: "UPDATE_AUTH", data }; }
然后去store/index.js中去使用 新增代码
import { createStore } from "redux"; import rootReducers from "../reducers/index"; export default function configureStore() { const store = createStore( rootReducers, window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__() : undefined ); return store; }
接下来了 就该去关联了 主入口文件index.js进行关联
import { Provider } from "react-redux"; import configtureStore from './store' const store = configtureStore(); Provider这个标签 要放在最外面进行包裹 <Provider store={store}> <App/> </Provider>
然后 你在哪个页面需要这个数据 再到这个页面进行关联
下面的方案是可以读取可以修改
import {connect} from 'react-redux' import * as authAction from '../actions/auth' import {bindActionCreators} from 'redux //这是读取 function mapStateToProps (state) { return { auth:state.auth } } //这是设置 function mapDisptachToProps (dispatch) { return { authActions: bindActionCreators(authAction, dispatch) }; }; export default connect(mapStateToProps,mapDisptachToProps)(App)
componentDidMount() { this.props.authActions.initAuth({ name:'测试' }) }
下面的方案是 只读取
import {connect} from 'react-redux' //这是读取 function mapStateToProps (state) { return { auth:state.auth } } export default connect(mapStateToProps)(App)