一旦React组件加载,我想更新同级元素。使用下面的示例,一旦加载PopupTable,我想将“数据尚未呈现”更改为“ Hello world”。
我的问题是,如果我尝试在render()调用期间更改状态,则会收到警告告诉我不要这样做,这是什么正确的处理方式?
class PopupBase extends React.Component {
render() {
return (
<div>
<div>
The data has not yet rendered.
</div>
<DataProvider endpoint="products/ajax/get_products_from_pickle" render={data =>
// Once the code get to here, I want to update the div above
<PopupTable data={data}/>
}/>
</div>
)
}
}
class DataProvider extends Component {
static propTypes = {
endpoint: PropTypes.string.isRequired,
render: PropTypes.func.isRequired
};
state = {
data: [],
loaded: false,
placeholder : this.props.placeholder
};
componentDidMount() {
fetch(this.props.endpoint)
.then(response => {
if (response.status !== 200) {
return this.setState({placeholder: "Something went wrong"});
}
return response.json();
})
.then(data => this.setState({data: data, loaded: true}));
}
render() {
const {data, loaded, placeholder} = this.state;
return loaded ? this.props.render(data) : <div>{placeholder}</div>;
}
}
export default DataProvider;
答案 0 :(得分:2)
一种解决方案是将您的代码更改为:
class PopupBase extends React.Component {
render() {
return (
<DataProvider
endpoint="products/ajax/get_products_from_pickle"
render={data =>
<div>
<div>
The data has { data ? "" : "not yet" } rendered.
</div>
<PopupTable data={data}/>
</div>
}/>);
}
}
更好的方法是将数据加载逻辑提取到高阶函数中。因此,您将拥有一个纯粹基于props进行渲染的纯react组件。还有另一个“包装器”组件(即DataProvider
),该组件从API加载数据并将data
属性提供给可视组件。