React Context API - children/consumers 可以请求提供者更改值吗?
React Context API - can children/consumers request that the provider change a value?
我以前用过 Redux,这次很想实现 Context API。我非常想做 React Context API - How to Get Reference To State Object In Provider For A Conditional Method 中描述的事情 - 但是,我希望 "change" 函数更通用 - 它最初看起来像这样:
class ProviderComp extends Component{
state={
name: "Gary",
age: 20,
color: "Red",
changeMind: ()=>{
if(this.state.color === "Red"){
this.setState({
name: "Tony",
age: 35,
color: "Blue"
})
}
if(this.state.color === "Blue"){
this.setState({
name: "Gary",
age: 20,
color: "Red"
})
}
}
}
但不是 "changeMind()",我想要 change(prop, val) 以便调用:
change("name","Bob")
会将 state.name 更改为 Bob
change("age", 30)
会将 state.age 更改为 30 等
这可能吗?我正在尝试做一些类似于 Redux 中的 child 发送更改请求,以及 parent reducer 接收请求并相应更新的事情。
我可能对上下文的想法是错误的,因为我不只是提供上游然后消费下游,我试图让下游消费者向提供者发回请求以改变事物 - 非常开放受过更好的思考方式教育!
为了更改提供程序值,<Provider>
应该重新呈现。所以这是关于制作一个组件来托管提供者来存储和更新状态:
class ProviderComp extends Component {
state = {
change: (key, val) => this.setState({ [key]: val }),
...
};
render() {
return <SomeContext.Provider value={this.state}>...</SomeContext.Provider>
}
}
是的,只需将更改函数也传递到上下文值中。
在包含上下文提供程序的组件中
changeMind = mind => this.setState({mind})
render() {
<Context.Provider value={{mind : this.state.mind, changeMind : this.changeMind}}>
</Context.Provider>
}
然后在有消费者的组件中,你可以调用context.changeMind
这将触发提供者值的变化,例如
<Context.Consumer>
{
contextValue => (<button onClick={contextValue.changeMind}>Change</button>)
}
</Context.Consumer>
我以前用过 Redux,这次很想实现 Context API。我非常想做 React Context API - How to Get Reference To State Object In Provider For A Conditional Method 中描述的事情 - 但是,我希望 "change" 函数更通用 - 它最初看起来像这样:
class ProviderComp extends Component{
state={
name: "Gary",
age: 20,
color: "Red",
changeMind: ()=>{
if(this.state.color === "Red"){
this.setState({
name: "Tony",
age: 35,
color: "Blue"
})
}
if(this.state.color === "Blue"){
this.setState({
name: "Gary",
age: 20,
color: "Red"
})
}
}
}
但不是 "changeMind()",我想要 change(prop, val) 以便调用:
change("name","Bob")
会将 state.name 更改为 Bob
change("age", 30)
会将 state.age 更改为 30 等
这可能吗?我正在尝试做一些类似于 Redux 中的 child 发送更改请求,以及 parent reducer 接收请求并相应更新的事情。
我可能对上下文的想法是错误的,因为我不只是提供上游然后消费下游,我试图让下游消费者向提供者发回请求以改变事物 - 非常开放受过更好的思考方式教育!
为了更改提供程序值,<Provider>
应该重新呈现。所以这是关于制作一个组件来托管提供者来存储和更新状态:
class ProviderComp extends Component {
state = {
change: (key, val) => this.setState({ [key]: val }),
...
};
render() {
return <SomeContext.Provider value={this.state}>...</SomeContext.Provider>
}
}
是的,只需将更改函数也传递到上下文值中。 在包含上下文提供程序的组件中
changeMind = mind => this.setState({mind})
render() {
<Context.Provider value={{mind : this.state.mind, changeMind : this.changeMind}}>
</Context.Provider>
}
然后在有消费者的组件中,你可以调用context.changeMind
这将触发提供者值的变化,例如
<Context.Consumer>
{
contextValue => (<button onClick={contextValue.changeMind}>Change</button>)
}
</Context.Consumer>