尽管在构造函数和super中传递了props,但仍未定义this.props

时间:2019-07-30 07:50:00

标签: reactjs

我正尝试访问this.props,但未定义

constructor(props) {
    super(props);
    console.log(this.props) <-- undefined
    this.state = {
        req: {
            userId: 1,
            skip: 0,
            limit: 10
        },
        posts: []
    }
}

通过

App.tsx 访问此组件

<Route path='/posts/:userId' component={() => <Posts />} />

我正在尝试通过this.props.match.params访问 userId 。我应该能够控制台 this.props ,但是由于某种原因它是不确定的。

3 个答案:

答案 0 :(得分:2)

您的https://{myoktadomain}/oauth2/default/v1/authorize不正确,

Route

您应该这样做

<Route path='/posts/:userId' component={() => <Posts />} />

<Route path='/posts/:userId' render={(props) => <Posts {...props} />} />

<Route path='/posts/:userId' component={(props) => <Posts {...props} />} />

最后,您可以在类似这样的组件中访问<Route path='/posts/:userId' component={Posts} />

props

更多info

答案 1 :(得分:0)

您的课程是否扩展了React.Component类?

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
  } 
}

答案 2 :(得分:0)

在构造函数中,传递给您的实例的参数为propsthis.props试图访问的是类的道具,而不是传递给构造函数的道具。

如果要显示默认情况下传递给组件的props,则应登录console.log(props),因为尚未定义this.props

如果您要在创建组件后显示道具(例如,由于父级的异步调用而多次渲染您的组件),则应将console.log放在render方法中