問題描述
為什麼我無法從反應上下文訪問變量?你能找出錯誤嗎? (Why am I not able to access variable from react context? Can you identify the mistake?)
我想訪問一個名為“currentNode”的數組。從反應上下文,但看起來它不起作用。控制台錯誤消息如下:
Unhandled Rejection (TypeError): Cannot read property '0' of null.
看來我無法從上下文訪問 currentNode 變量。你能找出錯誤嗎?非常感謝您的幫助。
第 1 步:這是代碼,我如何將其發送到上下文:
const AuthState = (props) => {
// auth state: create initial authState
const initialState = {
isAuthenticated: false,
chatId: null,
currentNode: [],
};
const fetchCurrentNode = async (chatId) => {
try {
const config = {
headers: {
"x‑auth‑token": "",
},
};
const res1 = await axios.get(
`http://localhost:4001/api/chatbots/${chatId}/nodeid`,
//`https://mybot.uber.space/api/chatbots/${chatid}`
//`https://sandbox.as.wiwi.uni‑goettingen.de/teachr/chatbots/pin/${pin}`
config
);
dispatch({
type: NEW_CURRENT_NODE_CREATED,
payload: currentNode,
});
} catch (error) {
console.error(error);
}
};
return (
<ChatContext.Provider
value={{
chatId: state.chatId,
chat: state.chat,
chatSessionId: state.chatSessionId,
createChatSessionId,
addBackendAnswerToChat,
addUserInputToChat,
resetChat,
fetchEventAnswerFromDialogflow,
fetchAnswerFromDialogflow,
}}
>
{props.children}
</ChatContext.Provider>
);
};
</code></pre>
第 1b 步:這是我的上下文聲明:
import React from 'react';
const chatContext = React.createContext();
export default chatContext;
</code></pre>
第 2 步:這是我將其保存為類型的方式:
export const NEW_CURRENT_NODE_CREATED = "NEW_CURRENT_NODE_CREATED";
第 3 步:這是我的減速器功能:
import { CHATID_FETCH_SUCCESSFUL, NEW_CURRENT_NODE_CREATED } from "./authTypes";
export default (state, action) => {
switch (action.type) {
case NEW_CURRENT_NODE_CREATED:
return {
...state,
isAuthenticated: true,
currentNode: [action.payload],
};
default:
return state;
}
};
</code></pre>
第 4 步:這就是我想要的訪問 currentNode 變量:
import AuthContext from "../../Context/Auth/authContext";
const authContext = useContext(AuthContext);
const { chatId, currentNode } = authContext;
console.log(chatId);
console.log(currentNode);
</code></pre>
參考解法
方法 1:
You didn't add value you are trying to use to the context value
return (
<ChatContext.Provider
value={{
chatId: state.chatId,
chat: state.chat,
currentNode: state.currentNode, // <‑‑ ADD THIS LINE
chatSessionId: state.chatSessionId,
createChatSessionId,
addBackendAnswerToChat,
addUserInputToChat,
resetChat,
fetchEventAnswerFromDialogflow,
fetchAnswerFromDialogflow,
}}
>
{props.children}
</ChatContext.Provider>
);
};
(by Rainer Winkler、iamawebgeek)
參考文件