简体   繁体   English

设置值在 reactjs useState 挂钩中滞后

[英]set Value is lagging in reactjs useState hook

export default function Content(props) {
  const [lookUp, setLookUp] = useState(null);
  return (
    <InputBase
      sx={{ ml: 1, flex: 1 }}
      placeholder="Search links"
      onChange={(e) => {
        //question is on the following two lines of code

        setLookUp(e.target.value);
        console.log(lookUp);
        if (true) {
          props.setLinkList(
            props.LinkList.filter((search) =>
              search.title.toLowerCase().includes(lookUp)
            )
          );
        }
      }}
    />
  );
}

NB: notice the comment of the code.注意:注意代码的注释。 As I've described from the code above, the two lines of code are what I'm asking.正如我从上面的代码中描述的那样,这两行代码就是我要问的。 eg) if I write "er", it logs "e" to the console.例如)如果我写“er”,它会将“e”记录到控制台。 then if "e" character and make it "ert" it console "er" to the console.然后如果“e”字符并将其设置为“ert”,它将控制台“er”到控制台。 setLookUp is lagging setLookUp 滞后

I want it to log "er" when I write "er" on my InputBase or Textfield.当我在 InputBase 或 Textfield 上写“er”时,我希望它记录“er”。 how can I achieve it.?我怎样才能实现它。? Anyone with the solution please?请问有人有解决办法吗?

Setting state is asynchronous in React.在 React 中设置 state 是异步的。

If you can use class components, you can use the 2nd argument of setState .如果可以使用 class 组件,则可以使用setState的第二个参数。

handleChange=(evt)=>{
    this.setState({lookUp: evt.target.value}, ()=> {
        // the 2nd argument of setState is a callback that is called after
        // the state update is over
        console.log(this.state.lookup);
        if(true) {
            this.props.setLinkList(
                this.props.linkList.filter((search) =>
                    search.title.toLowerCase().includes(this.state.lookUp)
                )
            );
        }
    });
}

Or if you have to use function components, you can use useEffect :或者如果你必须使用 function 组件,你可以使用useEffect

useEffect(()=> {
    console.log(lookUp);
    if (true) {
        props.setLinkList(
            props.LinkList.filter((search) =>
                search.title.toLowerCase().includes(lookUp)
            )
        );
    }
}, [lookUp]); // 2nd argument is dependency arry

Since lookUp is a dependency of useEffect it's run every time lookUp is updated.由于lookUp是useEffect 的依赖项,因此它在每次更新useEffectlookUp

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

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