【问题标题】:React Native Context反应原生上下文
【发布时间】:2020-04-28 10:17:39
【问题描述】:

我正在尝试创建一个上下文来保存来自 Api 响应的数据。但这给了我一个错误。 我不知道如何解决错误。 该画面是显示画面。在索引屏幕中,我可以使用另一个上下文并且效果很好。 我想创建另一个上下文来保存来自其他 Api 调用的数据。我正在尝试复制它,但它给了我一个错误。 谢谢。

TypeError: undefined is not an object (evalating '_useContext.state')

上下文

 import createDataContext from './createDataContext';
import jsonServer from '../api/api';

const currencyPrices = (state, action) => {
  switch (action.type) {
    case 'show_prices':
      return action.payload;
    default:
      return state;
  }
};

const showPrices = (dispatch) => {
  return async (id) => {
    const response = await jsonServer.get(`/prices/${id}`);

    dispatch({type: 'show_prices', payload: response.data[0]});
  };
};

export const {Context, Provider} = createDataContext(
  currencyPrices,
  {showPrices},
  [],
);

创建数据上下文

import React, {useReducer} from 'react';

export default (reducer, actions, initialState) => {
  const Context = React.createContext();

  const Provider = ({children}) => {
    const [state, dispatch] = useReducer(reducer, initialState);

    // actions === { addBlogPost: (dispatch) => { return () => {} } }
    const boundActions = {};
    for (let key in actions) {
      boundActions[key] = actions[key](dispatch);
    }

    return (
      <Context.Provider value={{state, ...boundActions}}>
        {children}
      </Context.Provider>
    );
  };

  return {Context, Provider};
};

屏幕

/* eslint-disable react-hooks/rules-of-hooks */
import React, {useContext, useEffect} from 'react';
import {View, Text} from 'react-native';
import {Context} from '../context/currencyPrices';
const showScreen = ({navigation}) => {
  const {state, showPrices} = useContext(Context);
  useEffect(() => {
    showPrices(1);

    const listener = navigation.addListener('didFocus', () => {
      showPrices(1);
    });

    return () => {
      listener.remove();
    };
  });

  return (
    <View>
      <Text>{state.length}</Text>
    </View>
  );
};

export default showScreen;

【问题讨论】:

    标签: reactjs react-native react-context


    【解决方案1】:

    在 app.js 中

    import {Provider  as ProviderName}
    
    <ProciderName>
    <App/>
    </ProviderName}
    

    你应该像 app.js 一样将提供者包装在 mani 根目录中

    【讨论】:

      猜你喜欢
      • 2020-09-25
      • 1970-01-01
      • 1970-01-01
      • 2020-12-19
      • 2021-02-25
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      • 2019-11-10
      相关资源
      最近更新 更多