React.useState用错误的状态重新渲染

时间:2020-04-11 03:14:58

标签: reactjs react-functional-component use-state

我有以下简化的代码可以控制我的仪表板

function App(props){
    const [role, setRole] = React.useState("guest");
    const [componentDrawerRender, setComponentDrawerRender] = React.useState(null);

    const handleSelectionDrawerClick = (component) => {

        setComponentDrawerRender(component);
        handleOpenComponentDrawer(true);
    };

    const handleLoginCallback = (user) => {

        if (user !== false) {
          handleCloseComponentDrawer();
          setRole(user.type);    <-- setting the new state does not work 
          console.log(val.type + " -> " + role );   <-- this here shows != values

        } else {
          //do nothing
        }
      };

    return (  
        <Button
        onClick={() => {
          handleSelectionDrawerClick(
            <LoginPage callback={handleLoginCallback} />
          );
        }}
      >
        LOG IN
      </Button>);
}

此代码的目的是打开一个抽屉(它完成),在抽屉中渲染一个组件(它完成),然后在用户使用该组件登录后关闭抽屉(它完成)并更新状态(几乎可以做到)。

该问题在handleLoginCallback方法内发生。好的数据将被发回,并且状态将使用好的数据进行更新。但是,仅页面上的某些组件被更新。

功能组件的重新渲染过程如何工作?它只是再次调用该函数还是仅以某种方式重新计算了返回值?下列代码不会在重新渲染时重新计算。可以让某些州依赖其他州吗?

const [mainList, setMainList] = React.useState((role) => {
    console.log(role);
    if (role === undefined || role === null) {
      return GuestListItems(handleSelectionDrawerClick);
    } else if (role === "customer") {
      return CustomerListItems;
    } else {
      return OwnerListItems;
    }
  });
下面的

<LoginPage>中调用回调方法的代码。

onSubmit(e) {
    e.preventDefault();

    this.setState({ isLoading: true });
    this.props.login(this.state, this.handleLoadingBar).then((retState) => {
      if(retState === null){
        this.props.callback(false);       <-- here 
      }else {
        this.props.callback(retState);    <-- here 
      }
    });
  }

2 个答案:

答案 0 :(得分:0)

在您的代码中,role的值在后续刷新(即函数调用)时更新,因为调用了setRole。原因有几个,因为角色在console.log行没有改变:

  1. role被标记为const;
  2. JavaScript在当前函数完成之前不会运行任何其他函数(更好的是:调用堆栈为空)。

还要对此进行检查:https://reactjs.org/docs/hooks-reference.html#functional-updates

useState钩子是一个正常函数,它获取一个参数并返回一个元组。尽管每次刷新都会调用该钩子(并因此调用参数),但参数值仅在第一次初始化时使用。

以下是API描述:https://reactjs.org/docs/hooks-reference.html#usestate

答案 1 :(得分:0)

onSubmit(e) {
    e.preventDefault();

    this.setState({ isLoading: true });
    this.props.login(this.state, this.handleLoadingBar).then((retState) => {
      if(retState === null){
        this.props.callback(false);       <-- here 
      }else {
        this.props.callback(retState);    <-- here 
      }
    });
  }

您正在将此函数的初始状态设置为no,而不是函数的结果。

相关问题