【问题标题】:OwnProps Match and Params are undefined React-Router V3OwnProps Match 和 Params 未定义 React-Router V3
【发布时间】:2018-05-02 08:16:56
【问题描述】:

试图从我的网址中获取id,以便我可以使用它来获取componentDidMount 上的数据。我还使用它在组件中设置一些状态以在页面上显示信息。但是,ownProps.matchownProps.params 都一直未定义。我已经尝试了很多东西,但我能想到的只是我的 / 路由在 thing/:id 之前匹配,这会导致问题吗?

(我可以使用其中任何一个,但它们都失败了)。 TypeError: this.props.params is undefined TypeError: this.props.match is undefined

这是我的路线:

export default (
  <Route path="/" component={App}>
    <Route path="login" component={requireNoAuthentication(LoginView)} />
    <Route path="register" component={requireNoAuthentication(RegisterView)} />
    <Route path="home" component={HomeContainer} />
    <Route path="thing/:id" component={ThingContainer} />
    <Route path="category" component={CategoryContainer} />
    <Route path="analytics" component={requireAuthentication(Analytics)} />
    <Route path="basic" component={requireNoAuthentication(BasicContainer)} />
    <Route path="*" component={DetermineAuth(NotFound)} />
  </Route>
);

mapStateToProps 在这里(我通常会注释掉thing,直到我找出问题所在,所以可以忽略那个问题)。我真正看到问题的是 const {id} 部分。

function mapStateToProps(state, ownProps) {
  console.log(ownProps);
  return {
    data: state.data,
    token: state.auth.token,
    loaded: state.data.loaded,
    isFetching: state.data.isFetching,
    isAuthenticated: state.auth.isAuthenticated,
    thing: state.things[ownProps.match.params.id],
  };
}

这是我的一个组件让我头疼的地方。

 @connect(mapStateToProps, mapDispatchToProps)
    export class Thing extends Component {
      constructor(props) {
        super(props);
      }

      componentDidMount() {
        const { id } = this.props.match.params;
        this.fetchData();
        this.props.fetchThing(id);
      }

顺便说一句,当我在上面console.log 它时,ownProps 就很好了。但是它缺少任何参数/匹配,这让我觉得它是预期匹配之前的路由匹配?这太荒谬了,因为我永远无法在不丢失 react-router 参数的情况下进行嵌套路由?

我现在已经到了我开始做这件事太久以至于失去注意力的地步。向一些很棒的人寻求帮助!

应用程序是 react 15.3,react-router v3,redux。

【问题讨论】:

    标签: javascript reactjs redux react-router


    【解决方案1】:

    mapStateToProps() 返回的props 对象应该包含ownProps.match,如果你想在你的组件中使用它。要么将其添加为另一个属性,要么将ownProps 合并到返回的对象中。

    【讨论】:

    • 我没有对此进行测试,但您可能是对的,它可以工作!我最终选择了上面的解决方案,因为它是预期的功能。我意识到我只是没有正确传递我的道具 =D。
    【解决方案2】:

    我看到您正在渲染“ThingContainer”,但您的类是“Thing”。你在哪里使用 HOC?你记得把所有的道具都传给孩子吗?

    例子:

    const ThingContainer = (props) => <Thing ...props />
    

    【讨论】:

    • 啊!太感谢了!我知道我因为看代码太久而发疯了,哈哈。果然,将道具传递到我的容器中,this.props.params 就出现了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 2018-09-10
    • 2016-07-31
    • 1970-01-01
    • 2022-06-28
    • 2017-10-04
    • 2017-08-08
    相关资源
    最近更新 更多