如何正确传递 React Components 中的 props?

我有路由数组,它传递到 RouteComponent


const info = [

  { path: '/restaurants/:id', component: <Restaurant match={{ params: '' }} /> },

  { path: '/restaurants', component: <ListRestaurant match={{ path: '/restaurants' }} /> }

];

我使用 Axios 连接后端


餐厅组件:


  async componentDidMount() {

    this.getOne();

  }

  getOne() {

    const { match } = this.props;

    Api.getOne('restaurants', match.params.id)

餐厅组件:


当我看到控制台时出现这样的错误

http://img4.mukewang.com/628ee8000001bd5f06270500.jpg

那么,什么可以作为道具传递呢?找不到解决办法。提前致谢


应用程序.js


import ...

import info from './components/info/routes';


class App extends Component {

  render() {

    const routeLinks = info.map((e) => (

      <RouteComponent

        path={e.path}

        component={e.component}

        key={e.path}

      />

    ));

    return (

      <Router>

        <Switch>

          {routeLinks}

        </Switch>

      </Router>

    );

  }

}

路由组件.js


import { Route } from 'react-router-dom';


class RouteComponent extends Component {

  render() {

    const { path, component } = this.props;

    return (

      <Route path={path}>

        {component}

      </Route>

    );

  }

}


RouteComponent.propTypes = {

  path: PropTypes.string.isRequired,

  component: PropTypes.object.isRequired,

};


繁星淼淼
浏览 95回答 2
2回答

互换的青春

好的,您需要做一些更改,但可能还不够。所以让我知道如果在评论中不起作用。第一步将组件正确发送到路由class RouteComponent extends Component {&nbsp; render() {&nbsp; &nbsp; const { path, component } = this.props;&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <Route path={path} component={component}/>&nbsp; &nbsp; );&nbsp; }}第二步发送 JSX 元素,而不是 JSX 对象const info = [&nbsp; { path: '/restaurants/:id', component: Restaurant },&nbsp; { path: '/restaurants', component: ListRestaurant }];

守着星空守着你

从 react-router-dom 导入 RouteProps 并将其用作 routecomponent.js 中 props 的接口。然后,不是通过表达式调用组件,而是像组件一样调用它,即例如,function Routecomponent({ component: Component, ...rest }: RouteProps) {&nbsp; &nbsp; if (!Component) return null;&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <Route&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {...rest}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Component {...props} />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;/>}&nbsp; &nbsp; )}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript