Лучший способ обновить вложенное состояние в контексте React - PullRequest
0 голосов
/ 23 апреля 2019

У меня проблемы с распознаванием обновлением вложенного состояния React. Я прочитал отличные ответы здесь , но все еще есть вопросы.

Я могу подтвердить, что изменение состояния выполняется и распознается в моих компонентах. Единственное, что я не вижу, это обновление React дерева, которое я обычно читаю, означает, что React не распознает мои обновления состояния (ищет только мелкие копии). Но React обновляет дерево достаточно, чтобы вызвать console.log() обновлений у моего потребителя.

Может быть, я не связываю что-то в нужном месте? Мой потребитель тоже довольно интенсивный, но в остальном работает. Также открыт для опций рефакторинга.

FilterContext:

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>

1 Ответ

1 голос
/ 27 апреля 2019

Обновления состояния не были проблемой - состояние обновлялось, как указано в вопросе. Моя проблема была в моем провайдере, где я ранее пытался сделать forEach() для return массива .map().

Прорыв был двояким: открытие метода .includes() было первой частью. Работа с условным выражением внутри .forEach() была для меня непростой задачей (и, вероятно, почему в DOM ничего не появлялось). .includes() по сути является условным оператором в сокрытии (содержит ли этот массив какой-либо из X?), Поэтому использование его внутри .filter() позволяет достичь того же.

Вторым прорывом было объединение методов массива (см. Больше здесь gomakethings ), в частности .filter() с .map(). Я не осознавал, что .filter() не возвращает массив в 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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...