【问题标题】:State doesn't update when Input changes输入更改时状态不更新
【发布时间】:2020-01-28 22:13:09
【问题描述】:

我有一个 Input 组件,它有一个函数 UpdateState 来处理更改。

  const UpdateState = e => {
setPayload([e.target.value]);
console.log("update state", payload);
};

问题是登录到控制台的状态始终是前一个,所以我第一次在 Input 字段中输入一个新值,状态仍然是空的,如果,例如,我添加一个空格 add结束,那么状态会切换到之前输入的字符串:

如何实现“实时”状态更新?

这是我使用之前附加的功能的组件:

<FormControl fullWidth className={classes.textArea}>
      <Input
        onChange={e => {
          UpdateState(e);
        }}
        defaultValue={payload}
      />
      <Button
        variant="contained"
        color="primary"
        className={classes.button}
        onClick={SubmitReview}
      >
        Submit{" "}
      </Button>
      {JSON.stringify(response.data.predictions)}
    </FormControl>

【问题讨论】:

    标签: reactjs react-hooks


    【解决方案1】:

    React.PureComponentuseStateReact.Componentthis.setState 一样是异步的。

    setPayload(e.target.value);
    console.log("update state", payload); //Value here not yet updated
    

    尝试使用useEffect

    useEffect(() => {
        // action on update of payload
        console.log(payload) // Value of payload will updated here
    }, [payload]);
    
    <Input
        onChange={e=> setPayload([e.target.value])}
        defaultValue={payload}
    />
    

    【讨论】:

      【解决方案2】:
      remove the [] array  try without the     `setPayload(e.target.value);`
      
       const UpdateState = e => {
          setPayload(e.target.value);
          console.log("update state", payload);
          };
      
          <FormControl fullWidth className={classes.textArea}>
                <Input
                  onChange={e=>
                    UpdateState;}
                  defaultValue={payload}
                />
                <Button
                  variant="contained"
                  color="primary"
                  className={classes.button}
                  onClick={SubmitReview}
                >
                  Submit{" "}
                </Button>
                {JSON.stringify(response.data.predictions)}
              </FormControl>
      

      告诉我它是否有效

      【讨论】:

      • 感谢您的帮助,不幸的是它的行为仍然相同。
      • 推项目可能对你有帮助
      猜你喜欢
      • 2021-09-27
      • 2021-11-27
      • 2019-05-31
      • 2016-09-23
      • 1970-01-01
      • 2020-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多