【问题标题】:How to update context state inside componentDidMount?如何更新 componentDidMount 中的上下文状态?
【发布时间】:2019-06-23 12:09:47
【问题描述】:

我很难将 Reduce 应用到我的项目中,我使用了上下文。

我创建了一个全局上下文。 我想在 componentDidMount 中更改全局上下文 tid。

请帮我做出改变。

GlobalContext.js

import React, {Component} from "react";

export const GlobalContext = React.createContext();

export class GlobalProvider extends Component {
    setTermId = process_id => {
            this.setState('0');
    };
    state = {
        userId: 'pvd-userid',
        tId: 'pvd-tid'

    }
    render() {
        return (
            <GlobalContext.Provider value={this.state}>
                {this.props.children}
            </GlobalContext.Provider>
        )
    }
}

ViewTem.js

import React, { Component } from 'react';
import { GlobalContext } from '../GlobalContext';


class ViewTem extends Component {
    constructor(props) {
        super(props);
    }

    async componentDidMount() {
        let cols = ['cc9900', 'cc0023'];
        const res = await fetch('http://localhost:9000/tview',{method:'POST', headers:{'Content-Type':'application/json'},body:{color: cols}});
        const conId = await res.text();
        /*
         * I want to put the 'conId' in the 'context.tid' and see the changes in the dev console and body.
        */
        console.log(' this.context:', this.context.tId);
    }

    render() {
        return(
            <div>
                connect id : 
                <GlobalContext.Consumer>
                    {value => value.userName}
                </GlobalContext.Consumer>
            </div>
        )
    }
}

ViewTem.contextType = GlobalContext;

export default ViewTem;

下面的 app.js 代码只展示了上下文传递方法的一部分。

app.js

....
<GlobalProvider>
    <App/>
</GlobalProvider>
....

初学者似乎很难理解 react 主页的上下文示例。 它还会混淆诸如状态和函数等名称的重复。

有没有简单易懂的代码示例?

提前谢谢你。

【问题讨论】:

  • 检查此代码一次stackblitz.com/edit/react-axjwa5,如果您不清楚,请告诉我,届时很乐意为您提供帮助
  • 感谢您的友好回答。 Coyp-Hello.js 的实现工作正常。我刚刚开始做出反应,所以我需要了解更多我注意到的代码。我可以在这里看到查询代码(stackblitz.com/edit/react-dy1bwf)。对不起,你能给我一个更清楚的答案吗?我想要的是在componentDidMount中将tid的值更改为“ctx-tid”并将其用于所有组件。

标签: reactjs react-context


【解决方案1】:

在 React 中,直接修改 this.state 是个坏主意,因为后续更新可能会覆盖您的更改。如果您通过上下文访问该状态,这同样适用!

documentation 建议同时传递一个更新函数作为值的一部分,该函数将在拥有提供程序的组件上调用 setState

import React, { Component } from "react";

export const GlobalContext = React.createContext();

export class GlobalProvider extends Component {
    setTermId = tId => {
        this.setState({ tId });
    };

    state = {
        userId: 'pvd-userid',
        tId: 'pvd-tid',
        setTermId: this.setTermId,
    };

    render() {
        return (
            <GlobalContext.Provider value={this.state}>
                {this.props.children}
            </GlobalContext.Provider>
        )
    }
}

然后您可以通过在消费组件中调用该函数来更新状态。

【讨论】:

  • 感谢您的回答。我尝试使用redux,但是太难了,我选择了context api。我可以使用组件中的更改,但我需要在整个应用程序中使用 ViewTem.js 中更新的 tid。所以我试图改变context.tid的值。有没有办法改成setState()?如果时间允许,可以在这里确认吗(stackblitz.com/edit/react-dy1bwf)?
  • 这里是a working version of your example - 请注意this.contextadded in React 16.6,而您的示例使用的是16.5,所以我必须升级它。
  • 还要注意this.context 有一些限制——主要的限制是你的组件只能读取一种上下文类型,即使它嵌套在多个上下文中。如果这不符合您的需求,您需要改用Consumer API。
  • React刚入手,感觉很多地方都欠缺。在发表评论之前,我进行了很多搜索,您的 cmets 确实有所帮助。我非常感谢你的帮助。 @joeClay
  • 很高兴我能帮上忙!如果你刚刚开始,我建议不要深入研究 contexts/Redux/etc。然而 - 对于很多应用程序,只使用组件和传递道具就足够了。当这种方法变得麻烦时,您应该使用 Context API 之类的东西。如果您还没有阅读,我建议您阅读 Lifting State UpThinking in React
猜你喜欢
  • 2017-04-25
  • 2016-03-01
  • 2020-08-16
  • 2018-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-25
  • 2020-11-06
相关资源
最近更新 更多