来自 child 的反应上下文没有改变
The react context from the child does not change
我阅读了类似问题的解决方案,但没有帮助。
这是我的简单代码:https://codesandbox.io/s/gracious-jennings-ugqzd
import myContext from "./myContext";
import Two from "./Two.js";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
number: 0
};
}
render() {
return (
<myContext.Provider value={this.state}>
<div className="App">
<Two />
<h2>{this.state.number}</h2>
</div>
</myContext.Provider>
);
}
}
export default App;
我需要对其进行设置,以便它可以在 class 中的任何位置更改变量号。
感谢帮助。
你不能只改变状态所以
componentDidMount() {
this.context.number = 100;
}
如果你改变状态,反应不会重新渲染,因为你改变了它。您可以执行以下操作:
在应用程序中:
import React from "react";
import "./styles.css";
import myContext from "./myContext";
import Two from "./Two.js";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
number: 0
};
}
increase = ()=> this.setState({number:this.state.number+1})
render() {
return (
<myContext.Provider value={{...this.state,increase:this.increase}}>
<div className="App">
<Two />
<h2>{this.state.number}</h2>
</div>
</myContext.Provider>
);
}
}
export default App;
一分为二:
import React from "react";
import myContext from "./myContext";
class Two extends React.Component {
static contextType = myContext;
render() {
return (
<myContext.Consumer>
{({ number,increase }) => <h1 onClick={increase}>{number}</h1>}
</myContext.Consumer>
);
}
}
export default Two;
我阅读了类似问题的解决方案,但没有帮助。
这是我的简单代码:https://codesandbox.io/s/gracious-jennings-ugqzd
import myContext from "./myContext";
import Two from "./Two.js";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
number: 0
};
}
render() {
return (
<myContext.Provider value={this.state}>
<div className="App">
<Two />
<h2>{this.state.number}</h2>
</div>
</myContext.Provider>
);
}
}
export default App;
我需要对其进行设置,以便它可以在 class
你不能只改变状态所以
componentDidMount() {
this.context.number = 100;
}
如果你改变状态,反应不会重新渲染,因为你改变了它。您可以执行以下操作:
在应用程序中:
import React from "react";
import "./styles.css";
import myContext from "./myContext";
import Two from "./Two.js";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
number: 0
};
}
increase = ()=> this.setState({number:this.state.number+1})
render() {
return (
<myContext.Provider value={{...this.state,increase:this.increase}}>
<div className="App">
<Two />
<h2>{this.state.number}</h2>
</div>
</myContext.Provider>
);
}
}
export default App;
一分为二:
import React from "react";
import myContext from "./myContext";
class Two extends React.Component {
static contextType = myContext;
render() {
return (
<myContext.Consumer>
{({ number,increase }) => <h1 onClick={increase}>{number}</h1>}
</myContext.Consumer>
);
}
}
export default Two;