【问题标题】:Array not re-rendering even after this.setState即使在 this.setState 之后数组也不会重新渲染
【发布时间】:2019-06-07 22:02:47
【问题描述】:

我已经设置了一个搜索栏作为子组件,并传递了两个道具,一个是我正在渲染的卡片数组,另一个是函数,它应该随着搜索字段的变化而设置状态。

<Searchbar quesCards={questionCards} filter={this.filter} /> :

现在这个questionCards 是一个包含要显示的卡片数组的状态变量。

questionCards.push(
     <QuestionCard
        id={i}
        question={question.question}
        answer={question.answer}
        isMarked={question.isMarked}
        isPublished={question.isPublished}
        validity={question.validity}
        category={question.category}
      />
  )

this.setState({ questionCards, newCards: questionCards, loading: false });

这里&lt;QuestionCard /&gt; 是另一个组件,但我相信它与问题无关。

在我的子组件中,我调用this.props.filter,过滤结果如下:

handleChange = name => event => {
  //filtering the data ...
  this.props.filter(newCards);
}

这是我在&lt;Searchbar/&gt;的onChange函数里面做的
回到父组件,

filter = (newCards) => {
  console.log(newCards); //displays the desired result
  this.setState({ newCards }); //the state changes, but is not rendered on screen
}

在这个 setState 之后,组件应该用新的结果重新渲染。但事实并非如此。
请注意,显示的是newCards,因为开头和questionCards仅用于传递prop
我已经尝试过this.forceUpdate
另外,如果我在函数 filter 内进行控制台日志,newCards 包含正确的结果,但在 this.setState({ newCards }) 之后没有重新渲染

【问题讨论】:

  • 那么searchBar组件接受了一系列问题,过滤器是做什么的呢?按属性过滤?
  • 搜索栏根据问题和搜索栏中的输入过滤结果。 ques.includes(event.target.value.toLowerCase());
    另一方面,prop 过滤器用于函数。如您所见,filter={this.filter}。所以this.props.filter(newCards) 调用函数filter 回到父组件中
  • 如果您将过滤器发送回来,它会过滤数组还是重新查询?
  • 过滤全部在子组件中进行,过滤后的结果作为参数传递给函数,准备在父组件中设置状态

标签: javascript reactjs


【解决方案1】:

我认为问题在于您的数据流效率低下。

您在 searchBar 中的过滤器输入应该更新一些过滤器状态(本地)。看起来只需要从您的过滤器状态中过滤问题。

&lt;SearchBar /&gt; 的消费者不需要知道过滤器。

const list = questions.filter(item => (
  // item.name[enter_property] === this.state.filter
))

然后.map() 在列表中。

你符合什么条件?一个或多个特定属性?

【讨论】:

    【解决方案2】:

    您正在生成这样的 QuestionCard

    questionCards.push(
         <QuestionCard
            id={i}
            question={question.question}
            answer={question.answer}
            isMarked={question.isMarked}
            isPublished={question.isPublished}
            validity={question.validity}
            category={question.category}
          />
      )
    

    但是,你更新了 newCards 状态变量,你能检查一下吗?

    如果没有解决,你可以发布你的完整代码吗?

    【讨论】:

    • this.setState({ questionCards, newCards: questionCards, loading: false }); 你错过了这条线吗?我也从一开始就显示newCards 变量
    猜你喜欢
    • 2020-02-18
    • 1970-01-01
    • 2019-03-05
    • 2022-11-04
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    相关资源
    最近更新 更多