gpt4 book ai didi

javascript - 如何等待在 react.js 中呈现 View 直到 $.get() 完成?

转载 作者:行者123 更新时间:2023-11-29 10:38:16 24 4
gpt4 key购买 nike

你好,我正在用 reactjs 编写一个聊天客户端,并希望使用从 REST 调用中检索到的数据来呈现我的组件。但是,我的组件在 REST 请求返回数据之前呈现;这会导致错误,因为我在我的子组件中调用 this.props。

var MainChat = React.createClass({
getInitialData: function(){
var c = []
$.get("http://127.0.0.1:8888/test/sampledata.php?user=123", function(data, status) {
console.log("Data: "+ data+ "\nStatus: " + status);
c = data
})
},
getInitialState: function() {
return {
chatId : "",
chats : this.getInitialData(),
//chats: this.props.chats
};
},
handleClickOnLeftUser: function(data){
console.log("handleClickOnLeftUser");
// console.log("chat id is");
// console.log(data.chatID);
this.setState({chatID: data.chatID});
},

render: function() {
console.log("main:render")
console.log(this.props.chats);


var theThreadIWantToPass = {};
for(var i = 0; i < this.state.chats.length; i++)
{
console.log("chat: " + this.state.chats[i].chatID);
if (this.state.chats[i].chatID === this.state.chatID) {
theThreadIWantToPass = this.state.chats[i];
break;
}
}

return (
<div className="chatapp">
<div className="thread-section">
<div className="thread-count">

</div>
<LeftUserList
chats={this.state.chats}
clickFunc={this.handleClickOnLeftUser} // ***important
/>
</div>
<div>
<RightMessageBox chat={theThreadIWantToPass} />
</div>
</div>
);
}
});

最佳答案

在您的情况下,您需要使用方法 componentDidMount , 像这样

var MainChat = React.createClass({

getInitialData: function() {
var url = 'http://127.0.0.1:8888/test/sampledata.php?user=123';

$.get(url, function(data, status) {
this.setState({ chats: data });
}.bind(this))
},

componentDidMount: function () {
this.getInitialData();
},

getInitialState: function() {
return {
chatId: '',
chats: []
};
},

handleClickOnLeftUser: function(data){
this.setState({ chatID: data.chatID });
},

render: function() {
var theThreadIWantToPass = {};

for(var i = 0; i < this.state.chats.length; i++) {
if (this.state.chats[i].chatID === this.state.chatID) {
theThreadIWantToPass = this.state.chats[i];
break;
}
}

return (
<div className="chatapp">
<div className="thread-section">
<div className="thread-count"></div>
<LeftUserList
chats={this.state.chats}
clickFunc={this.handleClickOnLeftUser} />
</div>

<div>
<RightMessageBox chat={theThreadIWantToPass} />
</div>
</div>
);
}
});

注意 - 使用"async": false 这是不好的做法

关于javascript - 如何等待在 react.js 中呈现 View 直到 $.get() 完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33327755/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com