【问题标题】:Rebuild ReactJs Component重建 ReactJs 组件
【发布时间】:2016-05-23 15:50:10
【问题描述】:

我的应用中有一个 reactjs 组件(compA),它调用另一个 reactjs 组件(compB)来挂载 compA。

在 compB 中,我有一个按钮,我需要在函数“componentDidUpdate”中销毁和重建 compA。

有人知道怎么做吗?


大概的代码是这样的,但是,在我的代码 compA 和 B 中,它们位于不同的文件中。

use strict';

var CompA = React.createClass({
    getDefaultProps: function() {
        return {
            name: 'location',
        }
    },
    render: function () {
        return <CompB name={this.props.name}/>;
    }
});

var CompB = React.createClass({
    getDefaultProps: function() {
        return {
            name: 'select'
        }
    },
    componentDidUpdate: function() {
        $('.button').click(function() {
            /*
             * RELOAD HERE COMPONENT
             */
        });
    },
    render: function () {
        return <div><select name={this.props.name}><option value="x">X</option><option value="y">Y</option></select><button id="button">Reload</button></div>
    }
});

ReactDOM.render(<CompA />, document.getElementsByID("compA"));
<html>
<body>
  <div id="compA"></div>

  <script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/js/bootstrap.min.js"></script>
  <script src="https://fb.me/react-0.14.7.js"></script>
  <script src="https://fb.me/react-dom-0.14.7.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>

  <script src="comp.jsx" type="text/jsx"></script>
</body>

【问题讨论】:

  • 如果我正确理解了您的答案,您可以在这种情况下使用setState 来触发重新渲染jsfiddle.net/_alexander_/69z2wepo/31153。或者你可以使用.forceUpdatejsfiddle.net/_alexander_/69z2wepo/31154
  • 我去分析,然后给你反馈!
  • @Alexander 还没有这个。我有一些细节没有放在代码中。 1)我还有一个组件来创建按钮并选择,多一级。 2) 对于选择挂载,我使用 ajax。
  • 你能澄清一下你想得到什么结果吗?
  • @Alexander 好的,我们走吧!我确实在我的应用程序中使用了我的选择组件。我创建了 3 个反应组件。首先,为ajax设置信息,如何选择url,选择名称;二、调用ajax require;第三,挂载 html 元素() 在我的应用程序中,我确实需要构造一个缓存。有了这个我需要重新加载ajax调用。并重新填充我的选择。

标签: reactjs components mount rebuild


【解决方案1】:

您不能从 CompB 重建整个 CompA,但从 CompB 调用 setState 将重建 CompB,在您的情况下,整个 CompA (因为您在其中没有任何其他内容)。

如果您想从 Ajax 源重新构建组件,您可以查看: React Js: How to reload the initila data loaded via ajax?

【讨论】:

  • 完美!通过调整代码解决了我的问题!咳咳!
猜你喜欢
  • 2021-11-20
  • 2023-04-11
  • 2020-06-20
  • 2019-01-01
  • 1970-01-01
  • 2018-01-23
  • 2018-09-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多