useState 不会在 React 中更新它的值

useState doesn't update its value in React

我想更新来自套接字的 listsetList 不起作用。 是关闭的东西吗?那我该如何解决呢?

function List(props) {
  const [list, setList] = useState([]);

  useEffect(() => {
    if (props.socket) {
      props.socket.on("list", (data) => {
        setList(data);
      });
    }
  }, [props.socket]);

  const renderList = (list) => {
    if (!list) return null;
    

    list.map((room) => {
      return <Room pop={room.length} />;
    });
  };

  return <div>{renderList()}</div>;
}

您不应该为 renderList 函数使用参数。通过这样做,您在其中引用的 list 指的是该参数,而不是状态值。您也没有 return 从那个函数中获取任何东西,您没有 return 调用 .map。尝试这样的事情:

const renderList = () => {
  if (!list) return null;

  return list.map((room) => <Room pop={room.length} />);
};

还要确保 props.socket.on(...) 函数实际触发并调用状态更新函数

编辑:正如其他人提到的,检查你的依赖关系 useEffect。我猜 props.socket 本身实际上并没有改变,所以你最终可能会得到陈旧的数据

是的,它是一个封闭的东西。尝试将您的列表状态包含在 useEffect 依赖项中。

查看此的答案以供参考