【发布时间】:2019-09-12 05:00:10
【问题描述】:
我在 React 识别嵌套状态更新时遇到问题。我已经阅读了excellent responses here,但仍有疑问。
我可以确认我的组件中正在发生并识别状态更改。我唯一没有看到的是 React 更新树,我读过这通常意味着 React 无法识别我的状态更新(只寻找浅拷贝)。但是,React 确实更新了足够多的树来触发我的消费者中的console.log() 更新。
也许我没有在正确的位置绑定一些东西?我的消费者也很紧张,但在其他方面工作。也对重构选项开放。
过滤器上下文:
import React from 'react';
export const FilterContext = React.createContext();
class FilterProvider extends React.Component {
constructor(props) {
super(props);
this.toggleEuphoric = () => {
this.setState(prevState => ({
...prevState,
emotions: {
...prevState.emotions,
anxious: false,
aroused: false,
calm: false,
cerebral: false,
creative: false,
energetic: false,
euphoric: true,
focused: false,
giggly: false,
happy: false,
hungry: false,
meditative: false,
mellow: false,
noemotion: false,
relaxed: false,
sleepy: false,
talkative: false,
tingly: false,
uplifted: false,
}
}))
},
this.state = {
emotions: {
anxious: null,
aroused: null,
calm: null,
cerebral: null,
creative: null,
energetic: null,
euphoric: null,
focused: null,
giggly: null,
happy: null,
hungry: null,
meditative: null,
mellow: null,
noemotion: null,
relaxed: null,
sleepy: null,
talkative: null,
tingly: null,
uplifted: null,
},
toggleEuphoric: this.toggleEuphoric,
}
}
render() {
return (
<FilterContext.Provider value={ this.state }>
{ this.props.children }
</FilterContext.Provider>
)
}
}
export default FilterProvider;
过滤消费者:
<FilterContext.Consumer>
{ filterToggle => (
// Check the emotions part of the FilterContext state object
// If all options are null, it means no interactions have taken place
// So we show all results using .map() over the pageContext.productData array coming out of gatsby-node.js
Object.values(filterToggle.emotions).every(item => item === null) ? (
this.props.pageContext.productData.map( (product) => {
return <ProductListItem
desc={ product.shortDescription }
handle={ product.handle }
image={ product.image }
key={ product.id }
productType={ product.productType }
strain={ product.strain }
tac={ product.tac }
tags={ product.tags }
title={ product.title }
/>
})
) : (this.props.pageContext.productData.map( product => {
emotion = Object.keys(filterToggle.emotions).find(key => filterToggle.emotions[key])
return product.tags.forEach( (tag) => {
tag.toLowerCase() === emotion &&
console.log(this),
<ProductListItem
desc={ product.shortDescription }
handle={ product.handle }
image={ product.image }
key={ product.id }
productType={ product.productType }
strain={ product.strain }
tac={ product.tac }
tags={ product.tags }
title={ product.title }
/>
}
)
}))
)}
</FilterContext.Consumer>
【问题讨论】:
-
也许您可以尝试先使用
Object.assign()定义新状态。然后使用该新对象调用setState()。这是为了确保新状态是一个全新的对象并触发重新渲染。发表评论是因为我不确定这是一个正确的答案,但可能值得一试。 -
@DimitrijAgal - 去想法,但结果完全相同。出于某种原因,React 只是没有看到更新。这也可能是我的消费者的东西,不确定。我的消费者非常复杂。
标签: javascript arrays reactjs react-context react-state-management