Redux,React

您所在的位置:网站首页 redux的数据流 Redux,React

Redux,React

2023-03-21 00:22| 来源: 网络整理| 查看: 265

上一章配置完React 中v6路由的抽离使用,那么在项目开发中需要统一管理数据,vue中使用的是vuex,而React 中使用的是 Redux(并不是react官方提供的库),react-redux,下面就将路由,redux,react-redux 来结合起来使用。

在项目下创建store文件夹:

一:创建 user.js 文件, 定义初始数据

const init = { todo: [ ] } const user = (state = init.todo, action) => { switch (action.type) { case "show": //展示 return state case "insert": //添加 return [...state, action.data] default: return state } } export default user

二:createStore.js 生成一个唯一的store函数

import { combineReducers,createStore } from "redux" import user from "./user" // 引入定义好的初始数据 const Reduser = combineReducers({ //提供合并多个reducer的函数,保证store的唯─性 user }) const store = createStore(Reduser) // createStore生成store export default store //导出store

三:创建reducers.js

import App from "../App" import { connect } from "react-redux" //connect: 将store和组件联系到一起,但是它并不会改变它连接的connect组价,而是提供一个 //经过包裹的connect组件( 就是connect包裹的组件就可以通过props来获取store数据) //读取数据,通过props接受 const mapState = (state)=>{     console.log(state) return {        //用state接受state数据 state:state.user } } // 可以通过触发yibu这个函数然后在调用dispatch进行触发,也可以在页面直接使用 //props.dispatch()来进行触发 const mapReduser = (dispatch)=>{ return { yibu:()=>{ dispatch({type:"show"}) } } } export default connect( mapState, mapReduser )(App)

四:配置根文件

redux和组件进行对接的时候是直接在组件中进行创建。react-redux是运用Provider将组件和store对接,使在Provider里的所有组件都能共享store里的数据,还要使用connect将组件和react连接。

import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; // import App from './App'; import App from "./store/reducers" //渲染reducers 因为已经使用connenct包裹 import reportWebVitals from './reportWebVitals'; import { BrowserRouter } from "react-router-dom" import { Provider } from "react-redux" import store from "./store/createStore" //引入store数据 const root = ReactDOM.createRoot(document.getElementById('root')); root.render( //使用Provider,使所有组件共享状态 ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals();

这时候在App页面打印props,

这时候store定义的数据就传过来了,因为我没写数据,所以数组为0,这时候就可以store来统一对数据的管理。

这时候会有一个问题,当跳转其他路由,比如home页面,home页面拿不到store。这时候只需要使用connect 将组件包裹一下, 这时候打印props就有数据了。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3