Don’t apply the react – story
Create a store file
- Index. js is used to create stores and application middleware, etc
Import {createStore} from 'redux' import reducer from './reducer. Js' export default storeCopy the code
- Reducer. Js creates a reducer(state, action) function that is passed to createStore to create a store.
// Return a reducer function that createStore uses to create a store. // Import the actiontypes.js type. Import {A, B} from './ actiontypes.js' // state Const defaultState = {valueA: ", valueB: State const reducer = (state = defaultState, action) => {if (action.type === A) {const newState = {... state} newState.valueA = action.value return newState } else if (action.type === B) { const newState = {... state} newState.valueB = action.value return newState } return state } export default reducerCopy the code
- Actiontypes.js is used to define the type of action objects in a unified way, which is convenient for unified management
Export const A = 'A' export const B = 'B'Copy the code
- Actionactionactionine.js is used to return the action object
Import {A, B} from './actionTypes' import {A, B} from './actionTypes' Export const setActionA = (value) => {return {type: A, value } } export const setActionB = (value) => { return { type: B, value } }Copy the code
- Used in the ReduxExample component
Import React from 'React' // import store import store from './.. /.. Action import {setActionA} from './.. /.. /store/actionCreators' class ReduxExample extends React.Component { constructor(props) { super(props) this.state = Store. The getState () / / listen to perform data change in the store the subscribe this. HandleStoreChange = this. HandleStoreChange. Bind (this) store.subscribe(this.handleStoreChange); } render() { return ( <div> <h2>redux-example</h2> <div> {this.state.valueA} </div> </div> ) } componentDidMount() { console.log(store.getState()) const actionA = setActionA('A') setTimeout(() => { store.dispatch(actionA) // Dispatch modify state, Log (this.state) console.log(store.getstate ())}, 1000) } handleStoreChange() { this.setState(store.getState()) } } export default ReduxExampleCopy the code
Use Chrome’s Redux DevTools plugin for easy development
// store/index.js import { createStore, compose } from 'redux' import reducer from './reducer' const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; Const store = createStore(Reducer, composeEnhancers()) export default storeCopy the code
Apply the react – story
- The installation
- use
Reference documentation
// app.js component import './ app.css '; import ReduxExample from './pages/reduxtest/Test' import { Provider } from 'react-redux' import store from './store' function App() { return ( <Provider store={store}> <ReduxExample/> </Provider> ); } export default App;Copy the code
// ReduxExample import React from 'React' // import action import {setActionA} from './.. /.. /store/actionCreators' import { connect } from 'react-redux' class ReduxExample extends React.Component { constructor(props) { super(props) this.state = { name: 'test' } } render() { const { valueA, changeValueA } = this.props return ( <div> <h2>redux-example</h2> { valueA } <button onClick={changeValueA}>change</button> </div> ) } } const mapStateToProps = (state) => { return { valueA: state.valueA, valueB: state.valueB } } const mapDispatchToProps = (dispatch) => { return { changeValueA: () => { dispatch(setActionA('A')) } } } export default connect(mapStateToProps, mapDispatchToProps)(ReduxExample)Copy the code
The Immutable. Js object is used to manage data in a store
- Effect: Ensures that state is not modified
- Reference documentation
- The installation
npm install immutable
oryarn add immutable
- FormJS converts JS objects into IMmutable objects, and then manipulates data via the set and GET methods provided by IMMUTABLE
// store/reducer.js // returns a reducer function that createStore uses to createStore // import actionTypes. Import {A, Import {fromJS} from 'immutable' const defaultState =. Import {fromJS} from 'immutable' const defaultState = FromJS ({valueA: ", valueB: "}) // state initialization // const defaultState = {// valueA: ", // valueB: "}) State const reducer = (state = defaultState, action) => { if (action.type === A) { return state.set('valueA', action.value) } else if (action.type === B) { return state.set('valueB', action.value) } return state } export default reducerCopy the code
// ReduxExample import React from 'React' // import action import {setActionA, setActionB} from './.. /.. /store/actionCreators' import { connect } from 'react-redux' class ReduxExample extends React.Component { constructor(props) { super(props) this.state = { name: 'test' } } render() { const { valueA, changeValueA } = this.props return ( <div> <h2>redux-example</h2> { valueA } <button onClick={changeValueA}>change</button> </div> ) } } const mapStateToProps = (state) => { return { valueA: state.get('valueA'), valueB: state.get('valueB') } } const mapDispatchToProps = (dispatch) => { return { changeValueA: () => { dispatch(setActionA('A')) dispatch(setActionB('B')) } } } export default connect(mapStateToProps, mapDispatchToProps)(ReduxExample)Copy the code
Use the redux-Thunk plug-in for asynchronous operations
Reference documentation
After dispatching an action and before arriving at the Reducer, additional actions are needed. You can use Redux Middleware for logging, creating crash reports, calling asynchronous interfaces, routing, and more. In other words, middleware is all enhancements to store.dispatch()
- Redux-thunk puts the asynchronous request into the actionCreators
- The Redux-Thunk middleware actually handles dispatches. Instead of returning objects, it now returns functions, which are automatically executed when the argument to Dispatch is a function.
- The installation
npm install redux-thunk
oryarn add redux-thunk
- use
// store/index.js import { createStore, compose, applyMiddleware } from 'redux' import reducer from './reducer' import thunk from 'redux-thunk' const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; Const store = createStore(Reducer, composeEnhancers(applyMiddleware(thunk)) export default storeCopy the code
Import {A, B} from './actionTypes' // returns an asynchronous function, Const waitRun = (val) => {return new Promise((resolve, reject) => {setTimeout(() => {resolve(val)}, Const setActionA = (value) => {return {type: const setActionA = (value) => {return {type: A, value } } export const setActionB = (value) => { return { type: B, value } } export const waitOneSeconds = (val) => { return (dispatch) => { waitRun(val).then(res => { const action = setActionA(res) dispatch(action) }) } }Copy the code
// ReduxExample component import React from 'React' // import action import {waitOneSeconds} from './.. /.. /store/actionCreators' import { connect } from 'react-redux' class ReduxExample extends React.Component { constructor(props) { super(props) this.state = { name: 'test' } } render() { const { valueA, changeValueA } = this.props return ( <div> <h2>redux-example</h2> { valueA } <button onClick={changeValueA}>change</button> </div> ) } } const mapStateToProps = (state) => { return { valueA: state.get('valueA'), valueB: state.get('valueB') } } const mapDispatchToProps = (dispatch) => { return { changeValueA: () => { dispatch(waitOneSeconds('A')) } } } export default connect(mapStateToProps, mapDispatchToProps)(ReduxExample)Copy the code
Use redux-saga for asynchronous operations
This is just a basic usage introduction, and I’m still learning more about it myself
- Redux-saga is used to handle asynchronous operations just like redux-thunk, but redux-Saga has a separate file to write to the API
Reference documentation
Chinese document
Other references
- The installation
npm install redux-saga
oryarn add redux-saga
Use of Redux-saga in detail