我遇到了React-Router和AJAX请求的问题。
这是index.js(条目文件):
import React from 'react';
import { render } from 'react-dom';
import { App } from './App';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import Utente from './routes/Utente';
import UtenteView from './routes/UtenteView';
render(
<Router history={browserHistory}>
<Route path="/" utente={mattia} component={App}>
<Route path="user/:id" component={User}>
<IndexRoute component={UserView}/>
<Route path="rete" component={Rete}></Route>
</Route>
</Route>
</Router>,
document.getElementById('root')
)
App.js文件只有render函数,返回
<div>{this.props.children}</div>
调用User组件。用户文件几乎相同。
在UserView.js文件中,我使用superagent
发出了一个AJAX请求import React, { Component } from 'react';
import request from 'superagent';
export default class UserView extends Component{
constructor(props) {
super(props);
this.state = {
result: null
};
this.fetchRequest = this.fetchRequest.bind(this)
}
makeRequest(id){
request
.get('/API/user/' + id)
.end(function(err, value){
if (value){
return({
result: JSON.parse(value.text).name
})
}
});
}
fetchRequest(){
this.setState(this.makeRequest(this.props.params.id));
}
componentDidMount(){
this.fetchRequest();
}
render(){
if(typeof this.state.result !== 'undefined'){
return(
<div>
<p>Questa è la pagina di {oggetto.id}</p>
</div>
)
}
return(
<div>
<h4>Loading data...</h4>
</div>
)
}
}
但这不起作用,而且它给了我错误:
Warning: setState(...): You passed an undefined or null state object; instead, use forceUpdate().
为什么呢?我认为错误在于我试图通过孩子来操纵父母的状态。
答案 0 :(得分:0)
问题是makeRequest
是异步的,您无法return
。你应该这样做:
makeRequest(id){
request
.get('/API/user/' + id)
.end((err, value) => {
if (value){
this.setState({
result: JSON.parse(value.text).name
})
}
});
}
另外,我会用你的组件做这样的事情。您不应该为您的设置覆盖构造函数。另外,请查看fetch:
import React, { Component } from 'react';
import fetch from 'whatwg-fetch';
export default class UserView extends Component{
componentDidMount() {
this.fetchRequest(this.props.params.id)
},
fetchRequest(){
fetch('/API/user/' + id)
.then((response) => {
return response.json()
})
.then((json) => {
this.setState({
result: json.name
})
})
.catch((ex) => {
console.log('parsing failed', ex)
})
}
getLoadingMessage() {
if(typeof this.state.result === 'undefined') {
return
}
return (
<div>
<h4>Loading data...</h4>
</div>
)
},
getMessage() {
if(typeof this.state.result !== 'undefined') {
return
}
return (
<div>
<p>Questa è la pagina di {oggetto.id}</p>
</div>
)
},
render(){
return (
<div>
{ this.getLoadingMessage() }
{ this.getMessage() }
</div>
)
}
}