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

How to update context state inside componentDidMount?

我很难将 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首页的context例子,初学者似乎很难看懂。 它还混淆了状态和函数等名称的重复。

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

提前致谢。

在 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>
        )
    }
}

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