如何在我的代码中使用 React-redux 来避免本地状态? [英] How to use React-redux to avoid local state in my code?

查看:70
本文介绍了如何在我的代码中使用 React-redux 来避免本地状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 redux,我已经写了一个简单的代码,它使用了 store、action 和 reducer.我正在使用 store.subscribe() 来监听状态的变化并用它来更新我的本地状态.

以下是我在 index.js 中的全部代码:

从'react'导入React;从 'react-dom' 导入 ReactDOM;从'redux'导入{createStore};var store = createStore(changeState);var 初始状态 = {数量:0,价格:0}函数 changeState(state = initialState, action) {开关(动作.类型){案例增量":var stateCopy1 = Object.assign({}, state);stateCopy1.qty = stateCopy1.qty + action.qty;stateCopy1.price = stateCopy1.price + action.price;返回 stateCopy1;默认:返回状态;}}class Home 扩展 React.Component {使成为() {返回 (<React.Fragment><Comp1/><br/><Comp2/></React.Fragment>)}}类 Comp1 扩展了 React.Component {增加 = () =>{var 动作 = {类型:'增量',数量:1,价格:100}store.dispatch(action);}使成为() {返回 (<button type="button" onClick={this.increase}>Increase</button>)}}类 Comp2 扩展了 React.Component {构造函数(){极好的();this.state = {购物车数量:0,购物车价格: 0}}使成为() {store.subscribe(() => {var globalState = store.getState();this.setState({cartQty:globalState.qty,cartPrice:globalState.price});})返回 (<div><h1>购物车中的商品总数:{this.state.cartQty}</h1><h1>购物车总价:{this.state.cartPrice}</h1>

)}}ReactDOM.render(, document.getElementById('root'));

我想使用 react-redux 来避免本地状态和订阅.我阅读了 connect() 和 mapStateToProps() 以及 .但是我无法弄清楚如何在下面的代码中使用它们.如何在我的代码中实现这些部分?

解决方案

您需要处理的事情很少.

首先,你需要安装一个 react-redux,然后在你传递 store 的顶层使用 Provider 组件

第二:需要连接需要访问storedispatch

的组件

第三:你需要渲染连接的组件

第四:您需要将 mapStateToProps 传递给访问 state 的容器,并需要将 mapDispatchToProps 传递给访问 dispatch 或使 action creators 可用作 props组件.如果您没有将 mapDispatchToProps 传递给 connect,默认情况下 dispatch 属性对组件可用.您可以在此处查看 API 文档

第五定义changeState reducer和initialState后创建store

从'react'导入React;从 'react-dom' 导入 ReactDOM;从'redux'导入{createStore};从'react-redux'导入{连接,提供者}var 初始状态 = {数量:0,价格:0}函数 changeState(state = initialState, action) {开关(动作.类型){案例增量":var stateCopy1 = Object.assign({}, state);stateCopy1.qty = stateCopy1.qty + action.qty;stateCopy1.price = stateCopy1.price + action.price;返回 stateCopy1;默认:返回状态;}}var store = createStore(changeState);类 Comp1 扩展了 React.Component {增加 = () =>{var 动作 = {类型:'增量',数量:1,价格:100}this.props.dispatch(action);}使成为() {返回 (<button type="button" onClick={this.increase}>Increase</button>)}}const Comp1Container = connect()(Comp1);类 Comp2 扩展了 React.Component {使成为() {返回 (<div><h1>购物车中的商品总数:{this.props.cartQty}</h1><h1>购物车总价:{this.props.cartPrice}</h1>

)}}const mapStateToProps = (状态) =>{返回 {购物车数量:state.qty,购物车价格:state.price}}const Comp2Container = connect(mapStateToProps)(Comp2);class Home 扩展 React.Component {使成为() {返回 (<React.Fragment><Comp1Container/><br/><Comp2Container/></React.Fragment>)}}ReactDOM.render(<Provider store={store}><Home/></Provider>, document.getElementById('root'));

工作演示

I am learning redux and I have put up a simple code which uses the store, action and reducer. I am using store.subscribe() to listen for changes in the state and using it to update my local state.

Below is my entire code in index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';

var store = createStore(changeState);
var initialState = {
    qty: 0,
    price: 0
}

function changeState(state = initialState, action) {
    switch (action.type) {
        case 'INCREMENT':
            var stateCopy1 = Object.assign({}, state);
            stateCopy1.qty = stateCopy1.qty + action.qty;
            stateCopy1.price = stateCopy1.price + action.price;
            return stateCopy1;
        default:
            return state;

    }
}

class Home extends React.Component {
    render() {
        return (
            <React.Fragment>
                <Comp1 /><br />
                <Comp2 />
            </React.Fragment>
        )
    }
}
class Comp1 extends React.Component {
    increase = () => {
        var action = {
            type: 'INCREMENT',
            qty: 1,
            price: 100
        }
        store.dispatch(action);
    }


    render() {
        return (
            <button type="button" onClick={this.increase}>Increase</button>
        )
    }

}
class Comp2 extends React.Component {
    constructor() {
        super();
        this.state = {
            cartQty: 0,
            cartPrice: 0
        }
    }
    render() {
        store.subscribe(() => {
            var globalState = store.getState();
            this.setState({cartQty:globalState.qty,cartPrice:globalState.price});
        })
        return (
            <div>
                <h1>Total items in cart: {this.state.cartQty}</h1>
                <h1>Total price of cart :{this.state.cartPrice}</h1>
            </div>
        )
    }
}

ReactDOM.render(<Home />, document.getElementById('root'));

I want to use react-redux to avoid the local state and subscription. I read about connect() and mapStateToProps() and . But I am unable to figure out how to use them in my below code. How can I implement these parts in my code?

解决方案

There are few things that you need to take care of.

First, you need to have a react-redux installed and then use Provider component at the top level to which you pass store

Second: You need to connect the components that need to access store or dispatch

Third: You need to render the connected components

Fourth: You need mapStateToProps to be passed to container which access state and mapDispatchToProps to accesses dispatch or make action creators available as props to components. In case you do not pass mapDispatchToProps to connect, by default dispatch prop is made available to the component. You can look at the API docs here

Fifth Create store after defining changeState reducer and initialState

import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { connect, Provider } from 'react-redux'

var initialState = {
    qty: 0,
    price: 0
}

function changeState(state = initialState, action) {
    switch (action.type) {
        case 'INCREMENT':
            var stateCopy1 = Object.assign({}, state);
            stateCopy1.qty = stateCopy1.qty + action.qty;
            stateCopy1.price = stateCopy1.price + action.price;
            return stateCopy1;
        default:
            return state;

    }
}

var store = createStore(changeState);

class Comp1 extends React.Component {
    increase = () => {
        var action = {
            type: 'INCREMENT',
            qty: 1,
            price: 100
        }
        this.props.dispatch(action);
    }


    render() {
        return (
            <button type="button" onClick={this.increase}>Increase</button>
        )
    }

}
const Comp1Container = connect()(Comp1);

class Comp2 extends React.Component {
    render() {

        return (
            <div>
                <h1>Total items in cart: {this.props.cartQty}</h1>
                <h1>Total price of cart :{this.props.cartPrice}</h1>
            </div>
        )
    }
}

const mapStateToProps = (state) => {
   return  {
      cartQty:state.qty,
      cartPrice: state.price
   }
}
const Comp2Container = connect(mapStateToProps)(Comp2);


class Home extends React.Component {
    render() {
        return (
            <React.Fragment>
                <Comp1Container /><br />
                <Comp2Container />
            </React.Fragment>
        )
    }
}
ReactDOM.render(<Provider store={store}><Home /></Provider>, document.getElementById('root'));

Working demo

这篇关于如何在我的代码中使用 React-redux 来避免本地状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆