gpt4 book ai didi

javascript - React 中动态生成的按钮不会重新渲染

转载 作者:行者123 更新时间:2023-11-28 04:42:26 25 4
gpt4 key购买 nike

我有两个按钮,一个 tweet 按钮和一个 facebook like 按钮。我希望在每个页面上显示这些内容。

第一次加载时,按钮加载得很好。但是,当我转到下一页时,按钮不再加载。此外,如果我返回,按钮将不再存在。

我已经追踪到这个事实 react-router 在新页面加载时不会重新渲染 DOM。由于这些按钮是用一些 JavaScript 生成的,因此不会再次触发。 JavaScript 将临时 div 替换为代表按钮的(有时很大)元素。

目前,我将 JavaScript 打包到 componentDidMount 中,以便每个按钮组件都能正确触发。如上所述,直到第二页为止,这都可以正常工作。此外,我尝试再次将代码放入 componentWillReceiveProps 中,但它没有改变任何内容。

如何让此代码再次运行,以便我可以在每个页面上显示我的社交按钮?

编辑:

这是我正在使用的示例组件:

class TwitterButton extends Component {
componentWillMount() {
this.twitterMessage = encodeURIComponent("test tweet");
}

componentDidMount(){
// Code from twitter's website for loading the button in
}

render() {
const twitterUrl = `https://twitter.com/intent/tweet?${this.twitterMessage}`;

return <a className="twitter-share-button" href={twitterUrl} />;

}
}

componentDidMount 中的代码在第一页中可以正常触发,但在第二页中却不能。

最佳答案

这看起来是一个众所周知的问题,如 react-router docs 中所述。 :

You may run into issues with components not updating after a location change despite not calling shouldComponentUpdate yourself. This is most likely because shouldComponentUpdate is being called by third-party code, such as react-redux's connect and mobx-react's observer.

With third-party code, you likely cannot even control the implementation of shouldComponentUpdate. Instead, you will have to structure your code to make location changes obvious to those methods.

发生这种情况是因为如果其 props 没有改变,react-redux 将不会重新渲染连接的组件。并且您的 componentWillReceiveProps 根本不会被调用。你需要做的是:

  1. 将当前位置传递给连接的组件,该组件应在位置更改时重新渲染。
  2. window.twttr.widgets.load() 添加到 componentDidMountcomponentDidUpdate 中,以便 Twitter 按钮初始值设定项同时完成其工作初始安装后和每次重新渲染后。

关于javascript - React 中动态生成的按钮不会重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43649312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com