lily-white / daily-work

0 stars 0 forks source link

17.redux #17

Open lily-white opened 5 years ago

lily-white commented 5 years ago

1.npm install react-redux redux redux-logger 2.新建actions、reducers、store文件夹 3.新建loginAction.js const LOGIN = 'LOGIN' export function login(user) { return { type: LOGIN, user } } 4.新建loginReducer.js import LOGIN from '../actions/loginAction'; const initialState = { user: null }

export default function login(state = initialState, action) { switch (action.type) { case LOGIN: return Object.assign({}, state, { user: action.user }) default: return state } } 5.在reducer文件夹下新建index.js import {combineReducers} from 'redux' import loginReducer from './loginReducer'; const rootReducer = combineReducers({ login:loginReducer }) export default rootReducer; 6.在App.js中引入 import { createStore } from 'redux' import {Provider} from 'react-redux' import reducer from './src/redux/reducers/loginReducer'; const store = createStore(reducer)

7.在Profile中加入 const useReducers = store => { return { login: store.login, }; }; export default connect(useReducers)(Profile); 就可以用const {login} = this.props;来获取reducers中的state了 参考链接