【问题标题】:React ajax and jsx反应 ajax 和 jsx
【发布时间】:2016-12-19 20:34:34
【问题描述】:

我用我的 ajax 请求结果填充的数组不会出现在我的 react 组件无序列表中。

当我对数组执行 console.log 时,我得到:

[] 0 : “事业”

1 : “技术职业中学”

2 : “新西兰职业生涯”

3 : “退伍军人职业 200”

4 : “北区健康职业高中”

5 : “芭比的职业生涯”

6 : “爱德华·肯尼迪健康职业学院”

7 : “伦敦大学职业小组”

8 : “职业顾问”

9 : "职业咨询服务"

长度 : 10

原型 : 数组[0]

当我在我的 react 组件中调用这个数组时,它不会呈现。下面是我的代码。

HTML

<div id="content"></div>

JS

// array that the titles will be loaded into
var response = [];

$.ajax({
    // request type ( GET or POST )
    type: "GET",

    // the URL to which the request is sent
    url: "https://en.wikipedia.org/w/api.php?",

    // data to be sent to the server
    data: {
        action: "query",
        format: "json",
        list: "search",
        srsearch: "careers",
        srwhat: "text",
        srprop: "timestamp",
        continue: "",
    },

    // The type of data that you're expecting back from the server
    dataType: "jsonp",
    crossDomain: true,
    // Function to be called if the request succeeds
    success: function (jsondata) {
        for (var i = 0; i < jsondata.query.search.length; i++) {
            //console.log( jsondata.query.search[i].title );
            //pushes each result into the array named list
            response.push(jsondata.query.search[i].title);
        }
    },
});

console.log(response);

var App = React.createClass({
    render: function () {
        //var title = list;
        return (
            <div>
                <h1>Hello World</h1>
                <p>The world is full of oppurtunity</p>
                <ul>
                    <li>{response[0]}</li>
                    <li>Freedom</li>
                    <li>Lozve</li>
                    <li>Money</li>
                </ul>
            </div>
        );
    },
});

ReactDOM.render(<App />, document.getElementById("content"));

这是我的代码笔的链接,我的所有代码都在其中,http://codepen.io/vhall_io/pen/vKQrQN/。我将 response[0] 插入到第一个 li 标记中,它不会呈现。请帮我渲染一下。

【问题讨论】:

  • 您在 ajax 调用返回之前调用了 render。把ReactDOM.render放在你的for循环之后
  • 感谢@azium 这确实有效。
  • 没问题。你知道为什么以前的方法不行吗?
  • 我相信是这样,据我了解,无序列表是在 ajax 调用返回请求之前创建的。 ul 元素一旦创建就无法修改。
  • UI 元素当然可以使用this.state 和this.setState 进行更改

标签: javascript arrays ajax reactjs jsx


【解决方案1】:

你必须更新状态。它不会渲染是你将它添加到变量中。因为它是 ajax 调用所以你的 html 首先呈现

【讨论】:

  • 这取决于,如果它的数据在任何事情之前只发生一次,当数据到达时可能会调用render。设置状态当然是个好方法。
  • 同意!我根据你的代码做了声明。当然,我的说法并不笼统。
  • 谢谢!我选择了@azium 的回答,因为它很好地解决了我的问题。
猜你喜欢
  • 2021-12-25
  • 1970-01-01
  • 2018-02-14
  • 2020-06-18
  • 1970-01-01
  • 2018-04-10
  • 2017-02-21
  • 1970-01-01
  • 2016-06-27
相关资源
最近更新 更多