在 Render 函数中传递 props

Passing props through in Render function

知道为什么我可以注销 'conditions' 变量但不能在渲染方法中将其作为 属性 传递吗?它始终未定义 - "cannot read property 'conditions' of undefined".

下面的代码。

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 一切都很好,那么我猜它在渲染发生之前没有接收到数据?

谢谢。

$.ajax 始终是异步的,因此 React 不可能使用有意义的 'conditions' 数组进行渲染。保持您当前的架构(这很好),只需在 ajax 回调中的 'conditions' 赋值之后移动渲染,或者如果您需要渲染初始的空状态,也可以将渲染代码移动到一个函数中并在两个地方调用它。

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