在渲染功能中传递道具

时间:2015-11-08 19:41:59

标签: properties reactjs jsonp render

知道为什么我可以退出条件'变量但不能将其作为render方法中的属性传递给它?它始终未定义 - "无法读取属性'条件'未定义"。

以下代码。

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')

);

如果我预先填充var一切都很好,那么我猜测它在渲染发生之前没有收到数据?

感谢。

2 个答案:

答案 0 :(得分:2)

$.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成功回调函数中传递适当的参数。

答案 1 :(得分:0)

$ .ajax总是异步的,因此React将无法使用有意义的'conditions'数组进行渲染。保持当前的体系结构(这很好),只需在ajax回调中的'条件'分配后移动渲染,或者如果需要渲染初始的空状态,也可以将渲染代码移动到函数内并在两个地方调用它

相关问题