React 中动态生成的按钮不会重新呈现

Dynamically generated buttons in React do not re-render

我有两个按钮,一个是 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.

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

  1. 将当前位置传递给连接的组件,这些组件应在位置更改时重新渲染。
  2. 将您的 window.twttr.widgets.load() 添加到 componentDidMountcomponentDidUpdate,以便推特按钮初始化程序在初始安装后和每次重新渲染后都能正常工作。