代码之家  ›  专栏  ›  技术社区  ›  jadlmir

如何在状态更改(父)reactjs上重新呈现子组件

  •  5
  • jadlmir  · 技术社区  · 8 年前

    我有一个数组列表
    登录子组件,返回初始数组。
    更改API中的数据后 componentDidMount
    我得到一个对象数组
    如果我将该数组记录在 render 作用
    它正在改变
    但子组件不是。
    我该怎么办??

    6 回复  |  直到 8 年前
        1
  •  3
  •   Daniel Artola    8 年前

    有几种方法可以做到这一点,但您基本上需要告诉您的子组件道具已经更新。

    一种方法是使用 shouldComponentUpdate

    shouldComponentUpdate(nextProps, nextState){
        return this.props.items[0] !== nextProps.items[0]);
    }
    

    你可能需要更好的检查 if 语句来查看数组是否已更改,但我想您已经明白了。

    您也可以使用 componentDidUpdate 或 componentwillreceiveprops 但如果更新状态将强制重新渲染,则会使用它们

        2
  •  3
  •   Arslan Tariq    8 年前

    您应该使用组件生命周期方法, componentWillReceiveProps 。 componentDidMount 仅在安装组件后调用一次。 组件将接收道具 道具更改时总是调用。如需参考,请访问: componentWillReceiveProps 。会是这样的:

    componentWillReceiveProps(nextProps) {
      if(this.props !== nextProps){
        // your code here
      }
    }
    
        3
  •  2
  •   pritesh    8 年前

    通常,当父组件中的状态发生更改时,会自动对子组件进行重新加载。 我创建了这个 jsfiddle 这很好用。

    阵列没有在子组件中更新的一个原因可能是,您只是在控制台中记录阵列,而没有将其用于DOM。为此,您可以尝试在子组件中使用数组中的内容,例如

    return (
        <div>this.props.Items[0].name</div>
    )
    

    所以这可能是一次。

    但是如果你想要控制台的话。不使用子组件中的数组元素打印log(),然后可以尝试

    componentDidUpdate() {
        this.forceUpdate();
    }
    

    因此,无论何时设置新状态或更新数据, componentDidUpdate 您可以尝试强制重新加载组件。尚未测试。

        4
  •  1
  •   Amanshu Kataria    8 年前

    只要状态发生更改,React本身就会重新渲染组件及其子组件。你不需要自己做这件事。但是,您可以通过使用 shouldComponentUpdate() 。

    检查 Does render get called any time “setState” is called?

        5
  •  1
  •   Tofazzal haque    6 年前

    我发现了一个很好的解决方案 钥匙 属性如果我们改变了 钥匙 属性,它将完全重新渲染。当您需要重新渲染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;
    
        6
  •  0
  •   sandeep.gosavi    4 年前

    您可以使用useState

    e、 g。

    export function myChildComponent({myValue}) {
       const [MyValue, setMyValue] = useState(null);
       useEffect(() => {
           setMyValue(myValue);
       }, [myValue])
    }