输入更改时状态不会更新

时间:2019-09-29 09:27:38

标签: reactjs react-hooks

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

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

问题是登录到控制台的状态始终是前一个状态,因此我第一次在输入字段中输入新值时状态仍然为空,例如,如果添加空格,最后,状态将切换到先前键入的字符串:

enter image description here

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

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

<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>

2 个答案:

答案 0 :(得分:0)

httpContext.User

function berechnen() { var rand = Math.floor(Math.random() * 100000000000) var sum = String(rand) var qsum = 0; for (var i = 0; i < sum.length; i++) { qsum += Number(sum.charAt(i)); } if (qsum == 50) { summe.text = String(sum); } else { berechnen() } 是异步的,就像useState的{​​{1}}一样。

React.PureComponent

尝试使用this.setState

React.Component

答案 1 :(得分:-1)

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>

告诉我是否可行