【发布时间】:2020-12-27 22:29:11
【问题描述】:
我正在努力实现某些目标,但我不确定这是不是最好的方法:
我有一个显示在<ProductDisplay /> 组件内的产品数组(productArray)。我还有一个<FilterPanel />,它允许我对productArray 中的元素进行排序。 <ProductDisplay /> 和 <FilterPanel /> 都包含在名为 <MainContainer /> 的 hoc 中,格式如下:
<MainContainer>
<FilterPanel />
<ProductDisplay />
</MainContainer>
<MainContainer /> 在它的 render() 方法中有一个排序函数。排序函数被传递给<FilterPanel />,当被调用时,它对productArray 进行排序。排序好的productArray从<MainContainer />传递到<ProductDisplay />
这里是<MainContainer />的简化代码:
//import sorting functions: categorySort, timeSort, and ratingSort
class MainContainer extends Component {
constructor(props) {
super(props)
this.state = {
sort: ""
}
}
render() {
const { productArray } = this.props; //getting an array of products from props
let sortResult = productArray; //if no sorting selected, sortResult will be the default order
const performSort = (sortType) => {
this.setState({sort: `${sortType}`}); //not really important
switch(sortType) {
case 'time':
sortResult = timeSort(productArray); //gets sorted when called
break;
case 'category':
sortResult = categorySort(productArray); //gets sorted when called
break;
case 'rating':
sortResult = ratingSort(productArray); //gets sorted when called
break;
default:
console.log('default case')
}
}
console.log( `sortResult final`);
console.log(sortResult); //does not reflect sorting done above; still in initial state
return (
<div>
<FilterPanel performSort={performSort}/>
<ProductDisplay sortResult = {sortResult} />
</div>
);
}
}
当从<FilterPanel /> 调用排序函数 'performSort' 时,它成功地在 switch 语句中生成了一个排序的 'sortResult' 数组,但是,switch 语句之外(之后)的 'sortResult' 没有改变(并且正在传递给<ProductDisplay /> 不变)。这很奇怪,因为 'sortResult' 应该在 switch 语句的范围内。
非常感谢任何帮助解决这个问题(此外,任何关于如何做得更好的建议。请注意,我还没有学习钩子,所以我更喜欢没有钩子的解决方案)。
【问题讨论】:
-
我相信为了重新渲染数据,您需要
setState。为什么不将sortResult添加到您的state对象中,并在switch、setState({sortResult})之后?另外,你的render方法为什么有这么多逻辑而不是render()之外的逻辑? -
我实际上把它放在了render里面,这样它就可以修改最初在那里初始化的'sortResult'。我想我现在明白了,除非我将“sortResult”放在状态中,否则它不会修改它,所以我将把函数移到 render() 之外
标签: javascript reactjs scope