如何更新componentDidMount内部的上下文状态?

时间:2019-01-30 09:00:15

标签: reactjs react-context

我使用上下文难以将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主页的上下文示例。 它还会混淆诸如状态和功能之类的名称重复之类的东西。

是否有一个简单易懂的代码示例?

谢谢。

1 个答案:

答案 0 :(得分: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>
        )
    }
}

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