使用故事书中的上下文反应

问题描述 投票:0回答:1

我正在尝试找出在React Storybook中实现上下文的正确方法。我的应用程序(不带故事书)使用的上下文如下:

import useAppContext, { providerPropTypes } from './hooks/useAppContext';
import AppContext from './contexts/AppContext';
function App() {
  const appContextValue = useAppContext();
  return (
    <AppContext.Provider value={appContextValue}>
      <Router>
        <Switch>
          <Route path="/myPath">
            <MyComponent />
          </Route>
        </Switch>
      </Router>
    </AppContext.Provider>
  );
}

AppContext.Provider.propTypes = providerPropTypes;

export default App;

其中useAppContext只是一个包含各种实用程序的函数:

export default function useAppContext() {
  const updateItem = (id, propertyToChange) => {...}
  ...
}

,MyComponent看起来像:


import React, { useContext } from 'react';
import AppContext from '../../contexts/AppContext';

function Cart() {
  const { items, ... } = useContext(
    AppContext
  );
  ...
  return (
    <div>[MyComponent]</div>
  )
}

[AppContext仅是:

import React from 'react';
export default React.createContext();

[为复合组件(页面)制作故事时,我正在尝试:

import React, { useContext } from 'react';
import useAppContext, { providerPropTypes } from '../../hooks/useAppContext';
import AppContext from '../../contexts/AppContext';

import MyComponent from './index';

export default { title: 'My Component' };

export const regular = () => {
  const appContextValue = useAppContext();
  return (
    <AppContext.Provider value={appContextValue}>
      <MyComponent />
    </AppContext.Provider>
  )
};

但是故事书(尽管将组件呈现在错误的后面)会引发错误:

React Hook "useAppContext" is called in function "regular" which is neither a React function component or a custom React Hook function

但是,如果我只是在没有任何上下文的情况下实现这个故事:

export const regular = () => {
  return (
    <MyComponent />
  )
};

我收到错误:

can't read property [items] of undefined

用上下文实现React函数组件的正确方法是什么,如何摆脱这个错误?

javascript reactjs react-context storybook
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.