React Native使用Context实现位置追踪时触发TypeError错误求助
解决React Native Context中的TypeError: Undefined not an object evaluating('_useContext.add_location')
看起来你遇到的问题是Context没有正确传递action函数,导致组件尝试访问add_location时拿到了undefined。让我们一步步排查和解决:
核心问题分析
错误提示里的add_location(全小写)和你代码里定义的add_Location(大写L)不一致,再看你的LocationContext.js,发现了一个关键的命名冲突:你把reducer函数命名成了LocationContext,这和你最终要导出的Context变量同名了!这种命名冲突会导致变量覆盖,使得Context对象无法正确包含你的action函数。
解决方案步骤
1. 修正Reducer函数的命名冲突
首先修改LocationContext.js里的reducer函数名,避免和Context重名:
import createDataContext from "./createDataContext"; // 将reducer函数重命名为locationReducer,避免和Context变量冲突 const locationReducer = (state, action)=>{ switch (action.type) { case 'add_current_location': return {...state, currentLocation: action.payload}; default: return state; } }; const add_Location = dispatch => (location) =>{ dispatch({type:'add_current_location', payload: location}) }; const startRecording = dispatch => () => { }; const stopRecording= dispatch =>()=>{ }; export const {Context, Provider}= createDataContext( locationReducer, // 这里传入修改后的reducer名称 {startRecording, stopRecording, add_Location }, {recording: false, locations:[], currentLocation:null} // 顺便把location:[]修正为locations:[],更符合语义 );
2. 确保Context被正确包裹
检查你的根组件(比如App.js),确保所有需要访问LocationContext的组件都被LocationProvider包裹:
import { Provider as LocationProvider } from './context/LocationContext'; import TrackCreateScreen from './screens/TrackCreateScreen'; export default function App() { return ( <LocationProvider> <TrackCreateScreen /> {/* 其他需要访问位置状态的组件 */} </LocationProvider> ); }
如果没有这一步,useContext(LocationContext)会返回undefined,自然无法解构出add_Location函数。
3. 验证createDataContext的实现
如果你自定义的createDataContext函数有修改action函数名的逻辑(比如转小写),那也会导致这个错误。确保它的实现是正确绑定action的,参考标准实现:
// createDataContext.js的标准实现示例 import React, { useReducer, createContext } from 'react'; export default (reducer, actions, initialState) => { const Context = createContext(); const Provider = ({ children }) => { const [state, dispatch] = useReducer(reducer, initialState); // 绑定dispatch到每个action函数 const boundActions = {}; for (const key in actions) { boundActions[key] = actions[key](dispatch); } return ( <Context.Provider value={{ ...state, ...boundActions }}> {children} </Context.Provider> ); }; return { Context, Provider }; };
4. 检查组件中的Context使用
确认TrackCreateScreen.js里的解构是正确的,和你定义的action函数名一致:
const { add_Location } = useContext(LocationContext);
额外优化建议
- 把初始状态里的
location:[]改为locations:[],更符合数组语义,避免后续混淆 - 可以给
add_Location函数添加类型检查,确保传入的location是有效数据
内容的提问来源于stack exchange,提问作者Malik Usman
相关产品推荐
相关产品推荐

