【发布时间】: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