【问题标题】:ReactJs context - how to replace the current component state with the state passed inReactJs 上下文 - 如何用传入的状态替换当前组件状态
【发布时间】:2019-01-12 03:21:44
【问题描述】:

我正在尝试了解 ReactJs 上下文,并终于在显示状态名称和 countNumber 方面取得了一些进展。

但我仍在努力找出如何替换当前状态,该状态在我的 formatCount() 函数中使用。

谁能让我知道您将如何在下面的示例中执行此操作?

我想在我的上下文中使用该数字,例如5 在方法中,formatCount(),所以它会像

    formatCount() {
        const currentCount = {c.state.currentCount};
        return currentCount === 0 ? "Zero" : currentCount;
    }

这是我的背景

import React, { Component } from "react";
export const CounterContext = React.createContext();

export default class CounterProvider extends Component {
    state = {
        state: { name: 'bob', currentCount: 5 },
    }
    render() {
        return (
            <CounterContext.Provider value={ this.state }>
                {this.props.children}
            </CounterContext.Provider>
        )
    }
}

这是我的计数器组件

import React, { Component } from "react";
import { RouteComponentProps } from "react-router";
import { CounterContext } from "../contexts/context.js";

export class Counter extends Component {
    state = { currentCount: 7 }

    render() {
        return <div className="m-2">
            <CounterContext.Consumer>
                {c =>
                    <div className="m-2">
                        <p>My name is {c.state.name} - {c.state.currentCount}</p>
                        <span className={this.getBadgeClasses()}>{this.formatCount()}</span>
                        <button className="btn btn btn-primary btn-sm m-2" onClick={() => { this.incrementCounter() }}>Increment</button>
                        <button className="btn btn-danger btn-sm m-2" onClick={() => { this.incrementCounter() }}>Delete</button>
                    </div>
                }
            </CounterContext.Consumer>
        </div>;
    }

    formatCount() {
        const currentCount = this.state.currentCount;
        return currentCount === 0 ? "Zero" : currentCount;
    }

    getBadgeClasses() {
        let classes = "badge m-2 badge-";
        classes += this.state.currentCount === 0 ? "warning" : "primary";
        return classes;
    }

    incrementCounter() {
        this.setState({
            currentCount: this.state.currentCount + 1
        });
    }
}

【问题讨论】:

    标签: javascript reactjs react-component react-context


    【解决方案1】:

    我不太确定您在这里对 CounterContext 的使用,如果我误读了问题,请见谅。

    当您说“状态已传递”时,您的意思是您正在尝试更新状态并显示更新后的状态吗?

    为此,您需要使用构造函数初始化您的状态:

    constructor() {
        super();
        this.state = {
          currentCount: 7
        };
      };
    

    然后您可以使用 this.setState({}) 更新状态。

    【讨论】:

    • 对不起,我认为我的措辞不是很好,我的意思是,我在 块中传递状态,我不想使用它我的组件的本地状态,这有意义吗?
    • 我添加了更多信息,有帮助吗?还是我需要将 formatCount 移出组件并将其放在上下文中?
    【解决方案2】:

    第一步是将要调用的方法(更新状态的方法)移动到CounterProvider 类。然后将该方法传递给状态对象。完成此操作后,您现在可以将 Counter 类更新为如下内容:

    <CounterContext.Consumer>
       {(c, methodName) =>
         <div className="m-2">
             My name is {c.state.name}
             <button onClick={methodName}></button>
         </div>
       }
    </CounterContext.Consumer>
    

    请注意,我使用了methodeName 并删除了修改过的CounterContext.Consumer 组件以简化操作。

    您可以阅读有关 Context API 的更多信息:https://reactjs.org/docs/context.html

    【讨论】:

    • 感谢您的评论,我已将其更改为以下内容,但这只是产生了空白结果。我没有在 onClick 上使用该函数,而是根据计数器值获取特定文本。
    • {formatCount}
    猜你喜欢
    • 2020-05-17
    • 2016-05-25
    • 1970-01-01
    • 2019-07-04
    • 2021-06-08
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 2016-12-24
    相关资源
    最近更新 更多