【发布时间】:2021-09-28 09:12:48
【问题描述】:
我遇到问题,每当我调用 getRoomDetails 时,在我的 useEffect 中,代码在完成从我的 API 获取数据之前会继续运行。因此,它将使用我为 boardState 提供的默认值创建 Chess 对象,而不是来自我的 API 的更新值。我怎么能得到它,所以它要等到 getRoomDetails 完成,然后再继续创建 Chess 对象。
const initialState = {
hostTime: 600,
guestTime: 600,
chessAnnotations: "",
isHost: true,
fen: "start",
}
const getRoomDetails = () => {
fetch('/api/get-room?code=' + roomCode).then((response) =>
response.json()
).then((data) => {
const newObj = {
hostTime: data.host_curr_time,
guestTime: data.guest_curr_time,
chessAnnotations: data.chess_annotations,
isHost: data.is_host,
fen: data.fen,
};
setBoardState(newObj);
console.log(newObj)
});
}
const [boardState, setBoardState] = useState(initialState);
let game = useRef(null);
useEffect(() => {
getRoomDetails();
console.log(boardState.fen + "lit");
game.current = new Chess(boardState.fen);
console.log("0");
}, []);
输出:
start 0
0
Object { hostTime: "600.00", guestTime: "600.00", chessAnnotations: "sdf", isHost: false, fen: "rnbqkbnr/pppppppp/8/8/8/3P4/PPP1PPPP/RNBQKBNR b KQkq - 0 1" }
【问题讨论】:
-
fetch在 JS 中执行异步,这意味着这完全是意料之中的。你想awaitfetch 以确保你可以在之前和之后运行代码。 -
你需要从
getRoomDetails返回fetch,并在调用它时使用.then。你应该在promise resolve之后运行的代码应该放在回调中 -
React setState 也是异步的
标签: javascript reactjs fetch use-effect