Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Redux in React projects

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces "how to use Redux in React projects". In daily operation, I believe many people have doubts about how to use Redux in React projects. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "how to use Redux in React projects". Next, please follow the editor to study!

What frameworks and tools will we use in the first place? React UI framework Redux state management tool, has nothing to do with React, other UI frameworks can also use Redux react-redux React plug-ins, function: facilitate the use of Redux react-thunk middleware in React projects, role: support asynchronous action

| |-- src |-- store Redux directory |-- actions.js |-- index.js |-- reducers.js |-- state.js |-- components component directory |-- Test.jsx |-- App.js project entry |

Step 1 of preparation: provide default values. Since Redux is used to manage data, the data must have default values, so we put the default values of state in the state.js file:

/ / state.js// declaration default value / / here we give two examples of synchronous data: pageTitle// asynchronous data: infoList (to be obtained by asynchronous interface in the future) export default {pageTitle: 'home', infoList: []}

Step 2: create a reducer, which is the data you really want to use in the future, and we will unify it in the reducers.js file

/ / reducers.js// tool function, used to organize multiple reducer And return the reducer collection import {combineReducers} from 'redux'// default import defaultState from'. / state.js'// A reducer is a function function pageTitle (state = defaultState.pageTitle, action) {/ / different action have different processing logic switch (action.type) {case 'SET_PAGE_TITLE': return action.data default: return state}} function infoList (state = defaultState.infoList) Action) {switch (action.type) {case 'SET_INFO_LIST': return action.data default: return state}} / / Export all reducerexport default combineReducers ({pageTitle, infoList// Welcome to join the full stack development communication circle to learn and communicate together: 864305860}) / / for 1-3 years front-end personnel / / to help break through the technical bottleneck Improve the ability of thinking

Step 3: create action, now that we have created reducer, but there is no corresponding action to manipulate them, so let's write action

/ / actions.js// action is also a function export function setPageTitle (data) {return (dispatch, getState) = > {dispatch ({type: 'SET_PAGE_TITLE', data: data})}} export function setInfoList (data) {return (dispatch, getState) = > {/ / use fetch to implement asynchronous request window.fetch (' / api/getInfoList', {method: 'GET') Headers: {'Content-Type':' application/json'}}) .then (res = > {return res.json ()}). Then (data = > {let {code, data} = data if (code = 0) {dispatch ({type: 'SET_INFO_LIST', data: data})}

Final step: create a store instance

/ / index.js// applyMiddleware: redux uses middleware through this function / / createStore: used to create store instance import {applyMiddleware, createStore} from 'redux'// middleware, function: if we do not use this middleware, when we dispatch an action, we need to pass the action object to the dispatch function; but if we use this middleware, we can pass in a function that takes two parameters: dispatch and getState. This dispatch can be used after the completion of future asynchronous requests. It is very useful for asynchronous action. Import thunk from 'redux-thunk'// introduces reducerimport reducers from'. / reducers.js'// to create a store instance let store = createStore (reducers, applyMiddleware (thunk)) export default store

Now that we have completed all the preparations for using Redux, we will use Redux in the React component.

First of all, let's write the entry file APP.js for the application.

/ / App.jsimport React from 'react'import ReactDOM from' react-dom'// lead-in component import TestComponent from'. / components/Test.jsx'// Provider is one of the two core tools of react-redux for passing store to components in each project / / the second tool is connect I will introduce import {Provider} from 'react-redux'// to the created store instance import store from' @ / store/index.js'// rendering DOMReactDOM.render (({/ * passing store as prop enables all components in the application to use store * /}), document.getElementById ('root'))

Finally, there is our component: Test.jsx

/ / Test.jsximport React, the function of the {Component} from 'react'// connect method: pass the extra props to the component and return the new component Components will not be affected in this process. Import {connect} from 'react-redux'// introduces actionimport {setPageTitle, setInfoList} from'.. / store/actions.js'class Test extends Component {constructor (props) {super (props)} componentDidMount () {let {setPageTitle SetInfoList} = this.props / / trigger setPageTitle action setPageTitle ('new title') / / trigger setInfoList action setInfoList ()} render () {/ / deconstruct store let {pageTitle from props InfoList} = this.props / / use store return ({pageTitle} {infoList.length > 0? ({infoList.map ((item)) Index) = > {{item.data}})}): null})}} / / mapStateToProps: map state to the component's props const mapStateToProps = (state) = > {return {pageTitle: state.pageTitle InfoList: state.infoList}} / / mapDispatchToProps: map dispatch to props of a component const mapDispatchToProps = (dispatch OwnProps) = > {return {setPageTitle (data) {/ / if you don't understand the logic here, please see the previous introduction to redux-thunk dispatch (setPageTitle (data)) / / execute setPageTitle will return a function / / this is what redux-thunk is used for: asynchronous action / / uplink code is equivalent to / * dispatch ((dispatch) GetState) = > {dispatch ({type: 'SET_PAGE_TITLE', data: data}) * /}, setInfoList (data) {dispatch (setInfoList (data))} export default connect (mapStateToProps, mapDispatchToProps) (Test) so far The study on "how to use Redux in React projects" is over. I hope I can solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report