【问题标题】:ReactJS: React-Router pass value to another pageReactJS:React-Router 将值传递到另一个页面
【发布时间】:2020-06-25 08:27:04
【问题描述】:

我需要使用 react-router 将一个值从一个页面传递到另一个页面。

我试过这样:

<li>
    <A 
      className="btn btn-link btn-sm"
      href={{ pathname: Routes.detail_page, search: `?_id=${C.Code}`, state: this.props.current  }}>
      { 'Open' }
    </A>
</li>

我会将 this.props.current 传递给详细信息页面。

在另一页中,如果我尝试在 componentDidMount() 中打印 this.props.current 它会导致未定义(当然在第一页中这个值是参数化的)。

constructor(props){
    super(props);
    this.state = {
    };
  }
componentDidMount(){
    let C = this.props.current
    console.log("C is: ", C) // this is undefined
    this.updateIsDeletableState()
  }

我该怎么办?

【问题讨论】:

  • 您可以添加您的“其他页面代码”吗?
  • 我只尝试在 componentDidMount() 中打印this.props.current ussign console.log。你需要了解什么? :)
  • 我想看看你是怎么编码的。
  • 我已经编辑了消息
  • 确保您的组件中有以下内容,您正在尝试访问道具:```constructor(props){ super(props); this.state = { //状态 }; } ```

标签: javascript reactjs react-router react-router-dom


【解决方案1】:

你必须确保你在Route中定义了URL参数

// file-where-you-define-routes.js
...
<Switch>
  <Route path={`your-path/:id`} component={YourComponent} />
</Switch>
...

然后使用钩子useParams获取参数

function YourComponent() {
  const { id } = useParams();
  let C = id;
  console.log("C is: ", C) // this should be defined now
  ...
}

或者如果你使用类组件this.props.match.params.id

class YourComponent extends Component {
  ...
  componentDidMount(){
    let C = this.props.match.params.id; // match
    console.log("C is: ", C) // this should be defined now
    this.updateIsDeletableState()
  }
}

【讨论】:

  • 另外,路由can声明也可以更新如下,通过render} /&gt;} /&gt;传递props &lt;Route exact path="/props-through-render" render={(props) =&gt; &lt;PropsPage {...props} title={Props
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多