【问题标题】:Pass this.state variable through App Context通过 App Context 传递 this.state 变量
【发布时间】:2020-03-24 14:29:00
【问题描述】:

当我使用函数 getData() 设置数组数据然后尝试在函数 updateData() 中调用它时,我收到一条错误消息,提示 this.state.data 未定义。关于如何将 this.state 变量从一个函数传递到应用上下文提供程序中的另一个函数有什么想法吗?

示例代码如下:

有什么想法吗?谢谢!

export class AppProvider extends React.Component {
         constructor(props) {
           super(props);
           (this.state = {
             data: [],
           });
         }

         getData = async () => {
            const data = "abc"
            this.setState({ 
                data,
            });
        }

        updateData = async () => {
          console.log(this.state.data)
}

         render() {
           return (
             <AppContext.Provider value={this.state}>
               {this.props.children}
             </AppContext.Provider>
           );
         }
       }

【问题讨论】:

  • 从您的函数中删除 async,因为它们不包含 await 关键字。
  • 方法 updateData 中没有任何异步,getData 异步可以删除。当你调用了 updateData??
  • 我很好奇,为什么要在构造函数的 this.state 周围加上括号?
  • 这一切都说得通。我已经修复了我的代码以包含您的 cmets。谢谢!
  • “我很好奇,为什么要在构造函数的 this.state 周围加上括号?”我在网上找到了一个例子,并以此为基础工作。我仍在努力真正了解发生了什么。但总而言之,你们帮助我到达那里。非常感谢!

标签: javascript arrays reactjs state


【解决方案1】:

我想说的三件事,

  1. 你想单独添加状态变量所以你想做value={{data:this.state.data}}
  2. 如果您打算在另一个组件中使用这些函数,您也希望将这些函数添加到 value 属性中
  3. 从函数中删除async,因为没有要解决的 Promise

      export class AppProvider extends React.Component {
          constructor(props) {
            super(props);
            this.state = {
              data: []
            };
          }
    
          getData = () => {
            const data = "abc";
            this.setState({
              data
            });
          };
    
          updateData = () => {
            console.log(this.state.data);
          };
    
          render() {
            return (
              <AppContext.Provider
                value={{
                  data: this.state.data,
                  getData: this.getData,
                  updateData: this.updateData
                }}
              >
                {this.props.children}
              </AppContext.Provider>
            );
          }
        }
    

在一个小例子中检查了这一点,CodeSandbox here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-11
    • 2011-10-19
    • 2014-12-25
    • 2015-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多