我有一個內容列表鏈接,當用戶單擊項目時,ajax請求被髮送到服務器,並且接收到的數據應該顯示在反應組件中。我用componentWillReceiveProps
發送我的請求,但刷新url不起作用(路由器不調用組件)。在反應組件中使用ajax渲染
它的index.js文件:
render((
<Router history={hashHistory}>
<Route path="/" component={App}>
<Route path="/content/:id" component={UmContent} />
</Route>
</Router>
), document.getElementById('root'));
它App.js文件的 「渲染」 功能:
render() {
return (
<div>
<h1>App</h1>
<ul>{this.renderItems()}</ul>
{this.props.children}
</div>
);
}
,它的UmContent.js文件:
export default class UmContent extends Component {
state = {
data: ''
}
componentWillReceiveProps(props) {
if (!props || !props.params || !props.params.id) {
return;
}
console.log(props.params.id);
let itemId = props.params.id;
let that = this;
$.ajax({
url: "http://192.168.78.2:8585/Default/mygetcontenttoactionresult/" + itemId,
type: 'GET',
dataType: 'html'
}).done((data)=> {
that.setState({data: data});
}).fail(()=> {
that.setState({data: <div> Something is wrong</div>});
});
}
render() {
return (
<div ref="aaa">
<UmC content={this.state.data}/>
</div>);
}
}
'componentWillReceiveProps'只會在組件實際獲取新道具時觸發。這發生在哪裏? –
@MichaelParker實際上我的組件應該使用url參數來更新自己,所以我認爲只是props.params被改變了。 – sahar
我不認爲你明白我想說什麼。 'componentWillReceiveProps'是[React生命週期](https://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops)的一部分,並且在組件被裝載時不會觸發*安裝後,組件獲得新的道具。你的ajax請求實際上是在發射嗎?如果是這樣,你的組件接收什麼道具才能做到這一點? –