反应本机上下文

时间:2020-04-28 10:17:39

标签: reactjs react-native react-context

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

TypeError:未定义不是对象(正在评估'_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;

1 个答案:

答案 0 :(得分:0)

在app.js中

import {Provider  as ProviderName}

<ProciderName>
<App/>
</ProviderName}

您应该将提供程序包装在像app.js这样的mani根中