【问题标题】:How do I force a child component to rerender when given new props values?给定新的道具值时,如何强制子组件重新渲染?
【发布时间】:2018-01-21 01:40:24
【问题描述】:

我已经尝试过这种模式。

ParentComponent
...
render(
return <ChildComponent newProps="newPropsValue />)

ChildComponent
...
ComponentWillReceiveProps{
this.setState({"propsKey": "newPropsValue"})
}

据我了解,初始组件渲染是由 props 更改触发的,并且由于 setState 是异步的(出于某种原因),因此不会在第一次通过时完成带有新状态更新的渲染。

但是我不明白为什么当它最终决定更新状态时,它不会重新渲染组件。我认为由 setState 引起的状态变化总是会触发重新渲染。

所以最后我有一个组件在状态实际改变之前无用地重新渲染,然后当/如果(?)状态更新时什么也不做。我完全不理解这种行为。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    setState 将触发 componentUdpate -> componentWillUpdate -> render。 props 更改将在此链之前触发 componentWillReceiveProps。您可以在这里查看有关React lifecycle 的图片。您可以看到 React 在 props 和 state 上的不同表现。

    所以:

    但是我不明白为什么当它最终决定更新状态时,它不会重新渲染组件。

    通过setState 更新state 将触发render 函数(重新渲染)。并且props 也会触发render。

    按照您的代码:

    1. componentWillReceiveProps:
      • this.props.newProps="newPropsValue"
      • this.state.propsKey="newPropsValue"
    2. render:和上面一样,没什么变化。
    3. 如果childComponent 设置propsKey 的任何事件setState (onClick, onChange ...)。假设setState({propsKey: "anotherValue"})。然后render 将再次被this.state.propsKey="anotherValue 和this.props.newProps="newPropsValue" 触发

    现在让我们在parentComponent 中更新您的childComponent 的props,假设newProps="latestPropsValue":

    1. componentWillReceiveProps 之前:
      • this.props.newProps="latestPropsValue"
      • this.state.propsKey="anotherValue"
    2. componentWillReceiveProps 之后:
      • this.props.newProps="latestPropsValue"
      • this.state.propsKey="latestPropsValue"

    当给定新的 props 值时,如何强制子组件重新渲染?

    如果您的render 使用的是state,则setState 在render 中。如果您在render 中使用props,它也会相应更新

    【讨论】:

    • 这不能回答我的问题。为什么状态变化不触发第二个周期?并重复我的问题:当给定新的 props 值时,如何强制子组件重新呈现?
    【解决方案2】:

    我使用 key 属性找到了一个不错的解决方案。如果我们更改了子组件或 React 组件的某些部分的 key 属性,它将完全重新渲染。当您需要根据 props 或 state 重新渲染 React 组件的某些部分或重新渲染子组件时,它将使用它。这是一个例子。我将重新渲染整个组件。

    import React, { useState, useEffect } from "react";
    import { PrEditInput } from "./shared";
    
    const BucketInput = ({ bucketPrice = [], handleBucketsUpdate, mood }) => {
      const data = Array.isArray(bucketPrice) ? bucketPrice : [];
      const [state, setState] = useState(Date.now());
      useEffect(() => {
        setState(Date.now());
      }, [mood, bucketPrice]);
      return (
        <span key={state}>
          {data.map((item) => (
            <PrEditInput
              key={item.id}
              label={item?.bucket?.name}
              name={item.bucketId}
              defaultValue={item.price}
              onChange={handleBucketsUpdate}
              mood={mood}
            />
          ))}
        </span>
      );
    };
    
    export default BucketInput;
    

    【讨论】:

      猜你喜欢
      • 2016-12-31
      • 2021-04-23
      • 2018-12-23
      • 2020-01-20
      • 1970-01-01
      • 2019-11-12
      • 1970-01-01
      • 1970-01-01
      • 2014-04-20
      相关资源
      最近更新 更多