【问题标题】:Why is my state not being updated using React Hooks?为什么我的状态没有使用 React Hooks 更新?
【发布时间】:2023-03-31 23:58:01
【问题描述】:

我正在尝试将我的状态设置为从 API 获取的数据。但是,当我 console.log 状态(在这种情况下为items)时,它返回一个空数组。

这是我的代码:

const Search = () => {
  const apiKey = 'xxxxxxx';
  const [input, setInput] = useState('');
  const [items, setItems] = useState([]);

  const handleSubmit = (e) => {
    searchAPI();
  };

  const searchAPI = async () => {
    const res = await fetch(`http://www.omdbapi.com/?apikey=${apiKey}&s=${input}`);
    const data = await res.json();
    setItems([data.Search]);
    console.log(items)
  };

  return (
    <form>
      <input onChange={(e) => setInput(e.target.value)}></input>
      <Link to={{ pathname: '/results', state: items }}>
        <button type="submit" onClick={handleSubmit}>
          search
        </button>
      </Link>
    </form>
  );
};

【问题讨论】:

标签: javascript reactjs react-hooks fetch


【解决方案1】:

setState() 将回调函数作为第二个参数,以确保更新状态。对于钩子,你需要这样做

useEffect(() => {
  console.log(items)
}, [items]);

【讨论】:

    【解决方案2】:

    因为 setState 是异步的

    setState() 并不总是立即更新组件。有可能 批处理或推迟更新。这使得阅读 this.state 在调用 setState() 之后立即出现潜在的陷阱

    https://reactjs.org/docs/react-component.html#setstate

    【讨论】:

      猜你喜欢
      • 2020-11-25
      • 2020-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多