[英]React Components Combined on Conditional Render
我有兩個相同類的React組件,它們有自己的狀態存儲數據。 我有條件地根據通過下拉更改傳播的父級(區域)的屬性來渲染組件。 在第一個下拉更改中,使用第二個組件的標題prop渲染該組件,但是使用第一個組件的數據渲染該組件。 在第二個下拉更改中,它按預期工作。
我已經嘗試過單獨測試組件,並且它們可以與區域屬性更改一起正常工作。 我還向其中一個組件中添加了一個道具,並添加了一個有條件的條件以防止在接收道具時重新渲染,但是得到了相同的結果。 我可以根據區域屬性來隱藏其中一個組件,但是我想通過條件渲染來實現。
var content = null;
if(this.props.region === 'WEST'){
content = (<Component title={'A'} region={this.props.region} dataSource={'someURL'} />);
}else{
content = (<Component title={'B'} region={this.props.region} dataSource={'someOTHERURL'} />);
}
return (
{content}
);
編輯更多詳細信息:
該組件在componentDidMount()和componentWillReceiveProps()上都對后端進行訪存調用,以更新組件的狀態。 當無條件呈現時,組件的每個實例(title = {'A'}和title = {'B'})都可以正常工作。 最初渲染的組件是否有可能嘗試在替換新組件的同時更新其狀態?
fetch('/table?tablename=' + this.props.tableName + '®ion=' +
nextProps.region + '&chartName=' + this.props.chartName, {
method: "GET",
headers: { "Accept": "application/json", "Content-Type": "application/json" }
}).then(res => res.json())
.then(data => this.setState({data: data}));
}
如果您使用的是ShouldComponentUpdate或PureComponent,則可能是造成問題的原因。 如果不查看更多代碼,就很難診斷問題。
在我看來,由於未觸發componentWillReceiveProps,組件的title屬性在第一次更改時就沒有更新。
如果沒有空間,我會在評論中注明,因為這不是答案。
您不必要地安裝/卸載組件,這增加了生命周期方法的復雜性。 我總是會返回一個組件,只是更改道具。 繼續獲取componentDidMount
和componentWillReceiveProps
但也考慮緩存響應。
所以也許像
const data = {
WEST: {
title: 'A',
url: 'someurl'
},
EAST: {
title: 'B',
url: 'anotherurl'
},
}
const dataSource = data[this.props.region];
return <Component title={dataSource.title} region={this.props.region} url={dataSource.url} />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.