javascript - ReactJs:如何从路由器路径链接获取正确的变量?

标签 javascript reactjs react-router

<Link to="/category/{card.title}">View List</Link>

在上面,我将路由从主页切换到类别页面,并尝试将 card.title 的值传递到类别组件

网址标题: enter image description here


然后在我的类别组件中:

constructor(props) {
    super(props);
    this.state = {
        title: props.title
    };

    console.log('props', props);
    console.log('props.location', props.location);
}

componentDidMount() {
    // console.log('Category componentDidMount this.state', this.state);
    console.log('%c Category componentDidMount this.state', 'background: #222; color: #bada55', this.state);
}

Prop :

enter image description here

最佳答案

card.title 是一个值,因此您需要像这样传递它:

<Link to={`/category/${card.title}`}>View List</Link>

或者像这样使用+:

<Link to={"/category/" + card.title}>View List</Link>

如果使用"",则整个部分将变成字符串,动态值将不会被替换。

检查mozilla doc有关模板文字的更多详细信息。

建议:

我建议您定义一个带有路由类别的参数,该参数的值为card.title,然后在类别组件内您可以通过this.props.params访问它。参数名称.

关于javascript - ReactJs:如何从路由器路径链接获取正确的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43920135/

相关文章:

javascript - 使用分页主干集契约(Contract)时获取

javascript - 计算另一个对象中对象的数量,javascript-json

javascript - 将正则表达式从 JavaScript 翻译成 ColdFusion?

reactjs - 嵌套可观察更改时组件不重新渲染

react-router - 使用带有基本名称的推送时的双基本路径

javascript - 从 webP 或 webM 渲染 VP8 帧

javascript - 在 ReactJS 中从子类访问父类方法

javascript - 从 express 后端获取后 react 未决的 promise

javascript - 如何部署React js单页应用程序(SPA)

javascript - React-router导致无法读取未定义的属性 'listen'