在 React 上下文中更新嵌套状态的最佳方式
Best way to update nested state within a React Context
我在 React 识别嵌套状态更新时遇到问题。我已通读 但仍有疑问。
我可以确认正在我的组件中进行并识别状态更改。我唯一没有看到的是 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>
状态更新不是问题 - 状态正在更新,如问题中所示。我的问题出在我的提供者身上,我之前试图在 .map()
数组的 return
上执行 forEach()
。
突破有两个方面:发现 .includes()
方法是第一部分。在 .forEach()
内部处理条件在我的问题中是行不通的(并且可能是 DOM 中什么也没有出现的原因)。 .includes()
本质上是 隐藏的条件语句 (这个数组是否包含任何 X?),因此在 .filter()
内部使用它可以实现相同的目的。
第二个突破是将数组方法链接在一起(查看更多信息 gomakethings),特别是 .filter()
和 .map()
。我没有意识到 .filter()
不是 return 到 DOM 的数组,所以我需要将 .map()
链接到它以显示结果。
我的新消费者,评论很多:
<FilterContext.Consumer>
{ filterToggle => (
console.log( ),
/**
* ==================
* No filters active
* ==================
* filterToggle gives us access to the context state object in FilterContext
* filterToggle.emotion is a nested object inside of state, which is bad practice but we need it
* Our filters have three states: null (initial), true if active, false when others are active
* This first line of code iterated through the filterToggle.emotions with Object.values
* .every() takes each value and looks to make sure all of them are null
* Using a ternary, if all emotions are null, we know to load all product objects into the DOM
* We pass them all down to ProductListItem component with a .map on productData coming out of gatsby-node.js
*
* ==================
* Filters active
* ==================
* If all the filterEmotions aren't null, that means some filter has been engaged
* .filter() is then used to filter down the list of products
* It's basically returning an array after checking a condition
* In our case, we want to see if the product.tags part of productData contains the active filter
* But how? Well, each filter has a key with it's name (like anxious, euphoric, etc)
* So we can run Object.keys(filterToggle.emotions) to get all the keys
* Then we run .find() over the keys, basically looking for the true one, which means that filter is engaged
* If that whole mess is true, we know the active filter and the current product in the array match
* That means the filter has found the right item and we want to display it
* To do the display, we have to pass that array over to a .map()
* .map() returns the filteredProducts straight into ProductListItem, iterating through each one
*/
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.filter( (product) => {
return product.tags.includes(
Object.keys( filterToggle.emotions )
.find(key => filterToggle.emotions[key])) === true
}).map( (filteredProduct) => {
return <ProductListItem
desc={ filteredProduct.shortDescription }
handle={ filteredProduct.handle }
image={ filteredProduct.image }
key={ filteredProduct.id }
productType={ filteredProduct.productType }
strain={ filteredProduct.strain }
tac={ filteredProduct.tac }
tags={ filteredProduct.tags }
title={ filteredProduct.title }
/>
})
)}
</FilterContext.Consumer>
我在 React 识别嵌套状态更新时遇到问题。我已通读
我可以确认正在我的组件中进行并识别状态更改。我唯一没有看到的是 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>
状态更新不是问题 - 状态正在更新,如问题中所示。我的问题出在我的提供者身上,我之前试图在 .map()
数组的 return
上执行 forEach()
。
突破有两个方面:发现 .includes()
方法是第一部分。在 .forEach()
内部处理条件在我的问题中是行不通的(并且可能是 DOM 中什么也没有出现的原因)。 .includes()
本质上是 隐藏的条件语句 (这个数组是否包含任何 X?),因此在 .filter()
内部使用它可以实现相同的目的。
第二个突破是将数组方法链接在一起(查看更多信息 gomakethings),特别是 .filter()
和 .map()
。我没有意识到 .filter()
不是 return 到 DOM 的数组,所以我需要将 .map()
链接到它以显示结果。
我的新消费者,评论很多:
<FilterContext.Consumer>
{ filterToggle => (
console.log( ),
/**
* ==================
* No filters active
* ==================
* filterToggle gives us access to the context state object in FilterContext
* filterToggle.emotion is a nested object inside of state, which is bad practice but we need it
* Our filters have three states: null (initial), true if active, false when others are active
* This first line of code iterated through the filterToggle.emotions with Object.values
* .every() takes each value and looks to make sure all of them are null
* Using a ternary, if all emotions are null, we know to load all product objects into the DOM
* We pass them all down to ProductListItem component with a .map on productData coming out of gatsby-node.js
*
* ==================
* Filters active
* ==================
* If all the filterEmotions aren't null, that means some filter has been engaged
* .filter() is then used to filter down the list of products
* It's basically returning an array after checking a condition
* In our case, we want to see if the product.tags part of productData contains the active filter
* But how? Well, each filter has a key with it's name (like anxious, euphoric, etc)
* So we can run Object.keys(filterToggle.emotions) to get all the keys
* Then we run .find() over the keys, basically looking for the true one, which means that filter is engaged
* If that whole mess is true, we know the active filter and the current product in the array match
* That means the filter has found the right item and we want to display it
* To do the display, we have to pass that array over to a .map()
* .map() returns the filteredProducts straight into ProductListItem, iterating through each one
*/
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.filter( (product) => {
return product.tags.includes(
Object.keys( filterToggle.emotions )
.find(key => filterToggle.emotions[key])) === true
}).map( (filteredProduct) => {
return <ProductListItem
desc={ filteredProduct.shortDescription }
handle={ filteredProduct.handle }
image={ filteredProduct.image }
key={ filteredProduct.id }
productType={ filteredProduct.productType }
strain={ filteredProduct.strain }
tac={ filteredProduct.tac }
tags={ filteredProduct.tags }
title={ filteredProduct.title }
/>
})
)}
</FilterContext.Consumer>