Storybook: Componente con enrutador react

Creado en 14 abr. 2017  ·  13Comentarios  ·  Fuente: storybookjs/storybook

¿Cómo puedo usar Storybook con componentes que usan React Router?

Ejemplo de componente

import React from 'react'
import PropTypes from 'prop-types'
import { Link } from 'react-router-dom'
import Brand from './components'

const Logo = ({children}) => {
  return (
    <Link to='/'>
      <Brand>
        {children}
      </Brand>
    </Link>
  )
}

Logo.propTypes = {
  children: PropTypes.string.isRequired
}

export default Logo

Error

screen shot 2017-04-14 at 4 27 22 am

Comentario más útil

Debes envolver tu historia en MemoryRouter usando la función addDecorator . Aquí hay un fragmento:

storiesOf('Logo', module)
  .addDecorator(story => (
      <MemoryRouter initialEntries={['/']}>{story()}</MemoryRouter>
  ))
  .add('normal', () => <Logo />)

Puede leer un ejemplo completo aquí: https://blog.hichroma.com/graphql-react-tutorial-part-5-6-ac36b6962a8a

Todos 13 comentarios

Debes envolver tu historia en MemoryRouter usando la función addDecorator . Aquí hay un fragmento:

storiesOf('Logo', module)
  .addDecorator(story => (
      <MemoryRouter initialEntries={['/']}>{story()}</MemoryRouter>
  ))
  .add('normal', () => <Logo />)

Puede leer un ejemplo completo aquí: https://blog.hichroma.com/graphql-react-tutorial-part-5-6-ac36b6962a8a

Vea este comentario aquí si desea enlaces para iniciar acciones de Storybook: https://github.com/storybooks/react-storybook/issues/485#issuecomment -294105214

Estaba buscando este error y me costó encontrar este problema porque se publicó en una imagen. Pegar el texto ahora para que las personas puedan encontrarlo más fácilmente en el futuro:

No se puede leer la propiedad 'historial' de indefinido
TypeError: no se puede leer la propiedad 'historial' de indefinido
en Link.render (http: // localhost: 9001 / static / preview.bundle.js: 52878: 35)
en http: // localhost : 9001 / static / preview.bundle.js: 43410: 21
en MeasuringLifeCyclePerf (http: // localhost: 9001 / static / preview.bundle.js: 42690: 12)
en ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (http: // localhost: 9001 / static / preview.bundle.js: 43409: 25)
en ReactCompositeComponentWrapper._renderValidatedComponent (http: // localhost: 9001 / static / preview.bundle.js: 43436: 32)
en ReactCompositeComponentWrapper.performInitialMount (http: // localhost: 9001 / static / preview.bundle.js: 42976: 30)
en ReactCompositeComponentWrapper.mountComponent (http: // localhost: 9001 / static / preview.bundle.js: 42872: 21)
en Object.mountComponent (http: // localhost: 9001 / static / preview.bundle.js: 4438: 35)
en ReactDOMComponent.mountChildren (http: // localhost: 9001 / static / preview.bundle.js: 42241: 44)
en ReactDOMComponent._createInitialChildren (http: // localhost: 9001 / static / preview.bundle.js: 40403: 32)

Aparece el siguiente error mientras uso MemoryRouter , y parece que MemoryRouter sale como undefined .

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.
Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.
    at invariant (http://localhost:6006/static/preview.bundle.js:2056:15)
    at createFiberFromElementType (http://localhost:6006/static/preview.bundle.js:27773:5)
    at createFiberFromElement (http://localhost:6006/static/preview.bundle.js:27718:15)
    at reconcileSingleElement (http://localhost:6006/static/preview.bundle.js:28966:19)
    at reconcileChildFibers (http://localhost:6006/static/preview.bundle.js:29065:35)
    at reconcileChildrenAtPriority (http://localhost:6006/static/preview.bundle.js:29715:30)
    at reconcileChildren (http://localhost:6006/static/preview.bundle.js:29706:5)
    at finishClassComponent (http://localhost:6006/static/preview.bundle.js:29842:5)
    at updateClassComponent (http://localhost:6006/static/preview.bundle.js:29814:12)
    at beginWork (http://localhost:6006/static/preview.bundle.js:30193:16)

¿Alguna idea de lo que podría estar pasando?

Hola @oyeanuj ,
¿Alguna noticia sobre esto? Tengo problemas bastante similares cuando uso Route .

@aperkaz No pude hacer que esto funcione todavía, así que sin incluir esos componentes en Storybook :( También esperaré una solución ...

Es posible que desee comprobar qué versión de enrutador de reacción está utilizando.

La solución de @shilman anterior funciona con react router 4.1.1 y @ storybook / react v 3.3.8

Para react-router 3:

// ...
import { Router, Route } from 'react-router';
import createMemoryHistory from 'react-router/lib/createMemoryHistory';

storiesOf('Foo', module)
  .addDecorator(story => (
    <Router history={createMemoryHistory('/')}>
      <Route path="/" component={() => story()} />
    </Router>
  ))
  .add('Default', () => <Foo />);

La respuesta aceptada funciona muy bien, pero obtengo

Uncaught ReferenceError: ___loader is not defined

Cualquier ayuda con este error

Para cualquiera que aterrice aquí en el futuro después de buscar en Google y arrancarse el cabello, permítame tal vez ahorrarle algo de tiempo.

El proyecto en el que estaba trabajando tenía una discrepancia de versión entre react-router (que estaba en "^ 4.1.1" en package.json) y react-router-dom , (que estaba en "siguiente").

Esto causó un problema en mi caso debido a que React cambió la forma en que this.context funciona, y react-router-dom siguiendo su ejemplo. Esto terminó con mi <Link /> tratando de extraer contexto mediante un método que aún no existía, y arrojando el excepcionalmente inútil "No debería usar un fuera de un" error.

Lo arreglé cambiando "react-router-dom": "next" por "react-router-dom": "^4.1.1" .

Para cualquier otra persona, lo que realmente me ayudó fue este paquete: https://github.com/gvaldambrini/storybook-router/

Muchas gracias, las respuestas ayudaron

Para cualquiera que use ganchos:

''
importar {createMemoryHistory} desde 'historial'
importar {Router, Route} desde 'react-router-dom'

const history = createMemoryHistory ({initialEntries: ['/']})

addDecorator (historia =>)

addDecorator (historia => (


))
''

¿Fue útil esta página
0 / 5 - 0 calificaciones

Temas relacionados

Olian04 picture Olian04  ·  78Comentarios

hansthinhle picture hansthinhle  ·  57Comentarios

moimikey picture moimikey  ·  67Comentarios

maraisr picture maraisr  ·  119Comentarios

firaskrichi picture firaskrichi  ·  61Comentarios