【问题标题】:react re-render component but not the whole page issue反应重新渲染组件但不是整个页面问题
【发布时间】:2018-09-16 04:55:47
【问题描述】:

我正在尝试在我的网页上重新渲染一个组件以做出反应,但我遇到了麻烦。当我单击后退按钮时,我想转到按字母顺序排列在当前部分之前的部分 - 我将组件的部分分解为字母。所以我的 handleBack 函数应该重新渲染组件。这是我下面的代码:

function handleBack() {
    const currentId = window.location.href.split('/').pop();

    const backId = String.fromCharCode(currentId.charCodeAt() - 1);

    return(

       <Route>

         <Redirect from={'/form/${currentId}'} to={'/form/${backId}'} />

       </Route>);

}

例如,它知道 currentID 是 B,backID 是 A,但它没有重新渲染组件并显示页面 A。为什么会发生这种情况?我该如何解决?我认为路由和重定向会起作用,但它什么也没做。

【问题讨论】:

  • 可以分享完整的组件代码吗?

标签: reactjs react-router


【解决方案1】:

第一

把它改成....

function handleBack() {
    const currentId = window.location.href.split('/').pop();

    const backId = String.fromCharCode(currentId.charCodeAt() - 1);

    return(

       <Route>

         <Redirect from={'/form/${currentId}'} to={'/form/${backId}'} />

       </Route>);

}

到...

function handleBack() {
    const currentId = this.props.match.params.id; // Use the route params instead of using window.location

    const backId = String.fromCharCode(currentId.charCodeAt() - 1);

    this.props.history.push('/form/${backId}');

}

【讨论】:

  • 这不起作用,因为它是一个函数,我没有使用任何道具。这给了我一个错误,因为它无法读取未定义的道具:(
  • 您可以强制刷新以查看代码this.forceUpdate() 的问题您可以将其放在constructor()componentDidMount()
猜你喜欢
  • 2019-02-07
  • 2016-07-13
  • 2020-03-08
  • 2018-12-27
  • 2018-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多