【问题标题】:How to update state of component provider using the Context API如何使用 Context API 更新组件提供者的状态
【发布时间】:2019-07-09 10:34:04
【问题描述】:

在函数的子组件中改变上下文的方法是什么?

我在mutating context from children 上阅读了一篇文章,其中解释了如何通过简单的事件处理程序来实现。即:

<MyContext.Consumer>
  <button onClick={() => setCount(count + 1)}>parent button +1</button>
</MyContext.Consumer>

但是,我想在子组件函数中更新父组件的函数(使用上下文)。

可以通过将该函数作为回调传递。


public anotherFunction(count, setCount) {
  // use the setCount here
  setCount(count + 1)
}

public handleClick(setCount) {
  // ..do some stuff to get the count
  let count = 10;
  this.anotherFunction(count, setCount);
}

render() {
  return(
    <MyContext.Consumer>
      <button onClick={() => this.handleClick(setCount)}>parent button +1</button>
    </MyContext.Consumer>
  )
}

现在这个例子有效。但是,在所有函数中都必须通过 setCount 函数似乎无关紧要。会不会有类似的事情发生?

public anotherFunction(count) {
  // perhaps something like this: 
  this.context.setCount(count + 1) // <- this doesn't work..
}

public handleClick() {
  // ..do some stuff to get the count
  let count = 10;
  this.anotherFunction(count);
}

render() {
  return(
    <MyContext.Consumer>
      <button onClick={() => this.handleClick()}>parent button +1</button>
    </MyContext.Consumer>
  )
}

还有其他更好的方法吗?

我已经创建了一个沙盒来更清楚地演示函数中的使用示例:

https://codesandbox.io/embed/suspicious-jackson-y3tk4?fontsize=14&module=%2Fsrc%2FMyForm.tsx

【问题讨论】:

  • handleClick()中可以直接调用setCount函数,为什么还需要anotherFunction?
  • 很明显这行得通:)。这只是一个例子。但是在“现实世界”的例子中,一些额外的东西是在一个函数中完成的。代码沙盒更接近实际代码。
  • 我已经给出了解决方案,让我知道这是否适合你:-)

标签: reactjs react-context


【解决方案1】:

上下文 api 的通用实现 -

在提供者中 -

this.state = {
      count: 0
    }

testFunction = (count) => {
// do whatever you want to do 
  this.setState({
    count: count + 1;
})

<AppContext.Provider
        value={{
         testFunction: this.testFunction,
        }}>
        <App />
      </AppContext.Provider>

在消费者中 -

export default props => (
    <AppContext.Consumer>
        {({testFunction}) => (
          <ChildComponent testFunction={testFunction} />
        )}
      </AppContext.Consumer>
);

然后,

export class ChildComponent extends React.Component { 
  // your component here

public anotherFunction(count) {
  // perhaps something like this: 
  const {testFunction} = this.props;
  testFunction(count);
}

public handleClick() {
  // ..do some stuff to get the count
  let count = 10;
  this.anotherFunction(count);
}

render() {
  return(
      <button onClick={() => this.handleClick()}>parent button +1</button>
  )
}
}

将函数作为道具传递给组件,并直接在您想要使用的地方使用它,而不是将其作为参数从一个函数传递给另一个函数:-)

【讨论】:

  • 谢谢。虽然我认为不完全是。这个想法是,在本例中,testFunction 将有一个触发器,该触发器可能会触发上下文中定义的函数。
  • 我已经使用消费者使用的 testFunction(在 Provider 中定义)更新了我的答案
  • 当你将它作为道具传递并在消费者中使用它时,它实际上会从提供者处执行。 (就像一个道具功能)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多