我有一個聊天組件,它使用 API 填充messages狀態,還有不同的區域有不同的聊天,我將它們作為道具傳遞給組件。在這個組件中,我有 3 個useEffects,但我對其中兩個不能正常工作的組件感興趣。在第一個 useEffect 中,我有一些代碼基本上將messages區域更改時的狀態重置為undefined. 我需要這樣做才能區分在我顯示加載組件<Spinner />的地方尚未調用 API 還是已調用 API 并且它已檢索空數組以顯示<NoData>組件。我遇到的問題是,當我更改區域時,useEffects會按應有的方式觸發,但第一個useEffect不會在調用messages第二個之前將狀態更新為未定義useEffect。由于歷史推送而重新渲染后,消息未定義,但第二個useEffect不再被觸發。我不明白為什么狀態沒有在useEffect第二個之前的第一個更新。同樣奇怪的是,這曾經對我有用,現在卻沒有。我在沒有推送到 git 的情況下更改了一些東西,現在我很困惑。下面的代碼:export default function ChatPage({ history, match, area, ...props }) { const [templates, setTemplates] = useState([]); const [advisors, setAdvisors] = useState([]); const [messages, setMessages] = useState(undefined); const [conversation, setConversation] = useState([]); const [chatToLoad, setChatToLoad] = useState(false); const [isOpen, setIsOpen] = useState(false); const [linkOrigin, setLinkOrigin] = useState(""); const [headerText, setHeaderText] = useState(""); // useEffect used to reset messages and conversation state // triggered on area change(messages and conversation reset) // and customer ID change(conversation reset). // Required to distinguish between API call not being made yet // and API returning no data. useEffect(() => { if (match.params.id) { setLinkOrigin(match.params.id); } if (messages) { if (match.params.id && messages.length !== 0) { let matches = messages.filter( (message) => message.ORIGINATOR === match.params.id ); if (matches.length !== 0 && match.params.id === linkOrigin) { setMessages(undefined); history.push("/chats/" + match.params.area); } } } setConversation([]); }, [area, match.params.id]); // API calls useEffect(() => { if (templates.length === 0) { api.getTemplates().then((templates) => { setTemplates(templates); }); } if (advisors.length === 0) { api.getAgents().then((advisors) => { setAdvisors(advisors); }); }
ReactJS:第一個 useEffect 在第二個被觸發之前不會更新狀態
陪伴而非守候
2022-07-08 17:06:42