繁体   English   中英

React Context API - 获取更新的状态值

[英]React Context API - get updated state value

我正在试验 React 上下文 api,

请检查我传递点击事件( updateName函数)的someComponent函数,然后从GlobalProvider函数更新state.name

更新state.name ,它将反映在浏览器上,但不会在控制台中获取更新的值(我在单击功能行下方调用了控制台以获取下面的更新值)

为什么不在该控制台中获取更新的值,但它正在渲染(在浏览器上)?

示例代码

App function
    <GlobalProvider>
      <Router>
        <ReactRouter /> 
      </Router>
    </GlobalProvider>

=== 2

class GlobalProvider extends React.Component {
  state = {
    name: "Batman"
  };
 
  render() {
    return (
      <globalContext.Provider
        value={{
          name: this.state.name,
          clickme: () => { this.setState({ name: "Batman 2 " }) }
        }}
      >
        {this.props.children}
      </globalContext.Provider>
    );
  }
}

export default GlobalProvider;

=== 3

const SomeComponent = () => {
     const globalValue = useContext(globalContext);
     
    const updateName = ()=> {
           globalValue.clickme();
           console.log(globalValue.name ) //*** Here is my concern - not getting updated value here but , getting updated value in browser  
     }


     return (
    <div onClick={(e)=> updateName(e) }>
       {globalValue.name}//*** In initial load display - Batman, after click it display Batman 2 
     </div>) }

React 状态不像 Vue 或 Angular 状态那样是观察者,这意味着您无法在更改它们后立即获得更新的值。

如果您想在更改后获得更新的值,您可以按照以下解决方案进行操作:

class A extends Component {
   state = {
     name: "Test"
   }

   updateName = () => {
     this.setState({name: "Test 2"}, () => {
       console.log(this.state.name) // here, name has been updated and will return Test 2
     })
   }
}

因此,您需要为 clickme 编写一个回调函数并按如下方式调用它:


class GlobalProvider extends React.Component {
  state = {
    name: "Batman"
  };

  render() {
    return (
      <globalContext.Provider
        value={{
          name: this.state.name,
          clickme: (callback) => { this.setState({ name: "Batman 2 " }, () => callback(this.state.name)) }
        }}
      >
        {this.props.children}
      </globalContext.Provider>
    );
  }
}

export default GlobalProvider;

并使用:

const SomeComponent = () => {
     const globalValue = useContext(globalContext);

    const updateName = ()=> {
       globalValue.clickme((name) => {
          console.log(name) // Batman 2
       });
     }


     return (
    <div onClick={(e)=> updateName(e) }>
       {globalValue.name}//*** In initial load display - Batman, after click it display Batman 2 
     </div>) 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM