為什麼我無法從反應上下文訪問變量?你能找出錯誤嗎? (Why am I not able to access variable from react context? Can you identify the mistake?)


問題描述

為什麼我無法從反應上下文訪問變量?你能找出錯誤嗎? (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) =&gt; {
  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 Winkleriamawebgeek)

參考文件

  1. Why am I not able to access variable from react context? Can you identify the mistake? (CC BY‑SA 2.5/3.0/4.0)

#react-context #javascript #reactjs #arrays






相關問題

在項目中使用 Context API 我以前會在異步操作創建者中使用 Redux? (Using Context API in a project I would have previously used Redux in - async action creators?)

Nextjs 和上下文 API (Nextjs and Context API)

從 redux-saga 函數訪問 React 上下文值 (Access React context value from redux-saga function)

如何在 Django 應用程序中用 react ContextAPI 替換 Redux (How can you replace Redux by the react ContextAPI in a Django App)

從深度嵌套的組件更新狀態而不重新渲染父組件 (Update state from deeply nested component without re-rendering parents)

更新 useContext 中的值時,組件不會重新呈現 (Component not re rendering when value from useContext is updated)

為什麼我無法從反應上下文訪問變量?你能找出錯誤嗎? (Why am I not able to access variable from react context? Can you identify the mistake?)

React Hook useEffect 缺少依賴項(在上下文中定義的函數) (React Hook useEffect has a missing dependency (function defined in context))

React Context 是道具鑽探的解毒劑嗎? (Is React Context an antidote for prop drilling?)

主題提供者問題 (Theme Provider issue)

打字稿反應上下文+類型'{}'沒有調用簽名 (Typescript react context + Type '{}' has no call signatures)

next.js socket.io 使用效果不更新套接字消息 (next.js socket.io useeffect not updating on socket message)







留言討論