知道为什么我可以注销“条件”变量但无法将其作为渲染方法中的属性传递吗?它始终是未定义的 - “无法读取未定义的属性‘条件’”。
代码如下。
var React = require('react');
var ReactDOM = require('react-dom');
import Square from '../components/square.jsx';
import Circle from '../components/circle.jsx';
import Weather from '../components/weather.jsx';
var conditions = [];
$.ajax({
url : "http://api.wunderground.com/api/xxxxxxxxxxxxxxxx/forecast10day/q/England/London.json",
dataType : "jsonp",
success : function(parsed_json) {
conditions = parsed_json.forecast.simpleforecast.forecastday;
console.log(conditions[1].conditions);
}
});
ReactDOM.render(
<div>
<h1>Hello React!!!</h1>
<SquareComp />
<Square />
<Circle width={100} height={100}/>
<Weather cityName={'London'} weatherConditions={conditions[1].conditions} />
</div>,
document.getElementById('rootNode')
);
如果我预先填充变量一切都很好,所以我猜测它在渲染发生之前没有接收数据?
谢谢。
最佳答案
$.ajax
是异步的。调用它后,它立即继续调用 ReactDOM.render
,并且,此时 conditions
仍然是一个空数组。您应该仅在 Ajax 调用完成加载从服务器发送的结果后才渲染组件。
尝试以下操作:
function renderConditions (conditions, domElement){
ReactDOM.render(
<div>
<h1>Hello React!!!</h1>
<SquareComp />
<Square />
<Circle width={100} height={100}/>
<Weather cityName={'London'} weatherConditions={conditions[1].conditions} />
</div>,
domElement
);
}
定义一个函数来呈现作为参数给出的数据。
$.ajax({
url : "http://api.wunderground.com/api/xxxxxxxxxxxxxxxx/forecast10day/q/England/London.json",
dataType : "jsonp",
success : function(parsed_json) {
conditions = parsed_json.forecast.simpleforecast.forecastday;
renderConditions(conditions, document.getElementById('rootNode'));
}
});
调用函数renderConditions
,并在ajax成功回调函数中传递适当的参数。
关于properties - 在 Render 函数中传递 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33598199/