【发布时间】:2018-12-05 09:13:38
【问题描述】:
我有一个产品 ID 列表和一个按钮。当我按下按钮时,我想刷新 ListComponent 中的数据。我不知道如何在 React 中做到这一点。有人可以帮我吗?
constructor(props) {
super(props);
this.state = {
products: this.props.productData //where productData an array of all products-ID
};
this.refresh = this.refresh.bind(this);
}
refresh() {
this.setState({ products: null });
this.forceUpdate();
}
render() {
const { products } = this.state;
<Button onClick={this.refresh} />
<ListComponent
data={products.map(entry => ({
text: entry.productId
}))}
/>
);
}
}
const mapStateToProps = (state, ownProps) => {
const products = selectAllProducts(state); //function that fetches-takes all products
return {
productData: products.map(products => ({
productId: product.get("productId")
}))
};
};
【问题讨论】:
-
如果您的
render方法依赖于 state 或 props 以外的数据,您只应该使用forceUpdate。在你的情况下它是没用的。 -
通过“刷新数据”您是否打算将产品属性设置为
null?还是有来自其他地方的新数据? -
@hindmost 好的!你能给我一个提示,我不知道如何刷新 ListComponent 的数据?
-
我将如何刷新 ListComponent 的数据.. 这取决于你的数据究竟来自哪里。
-
@djfdev 没有。我不想将产品属性设置为空。我真正想做的是刷新,因为可能会从其他地方添加一些新产品。我想将状态设置为 null 然后显示新状态,但这不是一个好方法。你知道我将如何刷新数据吗?
标签: javascript reactjs react-component