如何在React中更改全局变量的值?

时间:2016-10-28 09:45:12

标签: reactjs

我试图在React函数中更改全局变量的值但是我失败了。有人可以告诉我为什么以及如何制作aaa" ABC",非常感谢。

以下是代码:

var aaa = 123;

var MyValue = React.createClass({
    render: function(){
        aaa = "ABC";
        return <h1>{this.props.title}</h1>;
    }
});

ReactDOM.render(
    <MyValue title={aaa} />, //still 123
    document.getElementById('container')
);

2 个答案:

答案 0 :(得分:3)

您的问题

你在这里尝试做什么有很多问题。就像@JamesDonnelly所说,你需要研究React stateprop是如何工作的。

您似乎也误解了代码的流程是如何工作的。

var aaa = 123;

aaa变量的定义。

var MyValue = React.createClass({
    render: function(){
        aaa = "ABC";
        return <h1>{this.props.title}</h1>;
    }
});

绑定到变量MyValue的函数的定义 - 重要的是要理解你执行函数,你只是定义它。

ReactDOM.render(
    <MyValue title={aaa} />, //still 123
    document.getElementById('container')
);

您可以在此处渲染组件并运行上述功能。

由于这是代码流,因此您的作业aaa = "ABC"在之后发生,您调用了传递MyValue的{​​{1}}组件的呈现}支持title的值(仍为123)。

这可以通过以下代码证明。应用两次时,相同的精确代码会产生不同的值。同样,这是因为在第一次运行之后,您更改了aaa的值,因此在下次运行时结果会有所不同。

aaa
var aaa = 123;

var MyValue = React.createClass({
    render: function(){
        aaa = "ABC";
        return <h1>{this.props.title}</h1>;
    }
});

ReactDOM.render(
    <MyValue title={aaa} />,
    document.getElementById('container')
);

ReactDOM.render(
    <MyValue title={aaa} />,
    document.getElementById('container2')
);

如何修复

有点不清楚你想要实现什么,以及为什么要改变价值。但是,您可能希望查看React状态和props。官方页面上有一个可能对您有用的指南Thinking in React。另请查看setState()

祝你好运!

答案 1 :(得分:1)

绝对没有理由以这种方式使用反应,但here是最接近你想要的东西,但也非常hacky。

&#13;
&#13;
var MyValue = (function () {
    var mountedInstance;
    var aaa = 123;

    var MyValueInner = React.createClass({
    	componentDidMount() {
      	    mountedInstance = this;
        },
        render: function(){
          return <h1>{aaa}</h1>;
        },
		
    });
    
    MyValueInner.updateAAA = function (aaaNew) {
        aaa = aaaNew;
        mountedInstance.forceUpdate();
    }
    return MyValueInner;
})();

ReactDOM.render(
    <MyValue />,
    document.getElementById('container')
);

MyValue.updateAAA("ABC")
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="container"></div>
&#13;
&#13;
&#13;

All React components must act like pure functions with respect to their props以来,您无法改变组件内的道具。如果你想访问组件之外的某些全局状态,你应该寻求像redux或flux这样的解决方案。他们监听全局状态或存储并强制组件在发生更改时呈现。