如何使用 useEffect 的异步返回值作为 useState 中的默认值?

zem*_*rco 7 javascript reactjs react-hooks

我创建了一个简单的例子https://codesandbox.io/s/4zq852m7j0

如您所见,我正在从远程来源获取一些数据。我想使用返回值作为我的文本字段中的值。

const useFetch = () => {
  const [value, setValue] = useState("");

  useEffect(
    async () => {
      const response = await fetch("https://httpbin.org/get?foo=bar");
      const data = await response.json();
      setValue(data.args.foo);
    },
    [value]
  );

  return value;
};
Run Code Online (Sandbox Code Playgroud)

但是,在useState函数内部使用该值不起作用。我认为useState仅在第一次渲染时使用默认值。首次渲染时,该值显然未设置,因为它是异步的。文本字段应该有值,bar但它是空的。

function App() {
  const remoteName = useFetch();
  // i want to see the remote value inside my textfield
  const [name, setName] = useState(remoteName);

  const onChange = event => {
    setName(event.target.value);
  };

  return (
    <div className="App">
      <p>remote name: {remoteName}</p>
      <p>local name: {name}</p>
      <input onChange={onChange} value={name} />
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

从远程获取值后,我希望能够在本地更改它。

有任何想法吗?

Shu*_*tri 6

现在useFetch返回一个异步可用的值,您需要的是在 remoteValue 可用时更新 localState,为此您可以编写一个效果

const remoteName = useFetch();
  // i want to see the remote value inside my textfield
  const [name, setName] = useState(remoteName);
  useEffect(
    () => {
      console.log("inside effect");
      setName(remoteName);
    },
    [remoteName] // run when remoteName changes
  );

  const onChange = event => {
    setName(event.target.value);
  };
Run Code Online (Sandbox Code Playgroud)

工作演示