【问题标题】:REACT NATIVE / my child component don't re-render despite props changeREACT NATIVE / 尽管道具发生变化,我的子组件不会重新渲染
【发布时间】:2021-06-21 01:51:26
【问题描述】:

我在下面的代码中遇到了一个问题(这里是沙箱https://codesandbox.io/s/silly-rubin-9ghc5?fontsize=14&hidenavigation=1&theme=dark),道具发生了变化,但没有相应地刷新组件。

我希望能够在父节点的状态中跟踪不同的投票/选项,因此我使用一个数组,其中索引是我的选项的索引,值是投票数。

import { useEffect, useState } from "react";
import { Button, View } from "react-native";

import "./styles.css";

const myList = [
  {
    cid: 0,
    cTx: "Paris"
  },
  {
    cid: 1,
    cTx: "Lyon"
  },
  {
    cid: 2,
    cTx: "Marseille"
  },
  {
    cid: 3,
    cTx: "Valence"
  },
  {
    cid: 4,
    cTx: "Bordeaux"
  }
];

interface mTprop {
  myItemId: number;
  myItemTxt: string;
  myItemSt: number[];
  myItemClck: () => void;
}

const MyItem = (props: mTprop) => {
  const onBtPress = () => {
    props.myItemClck();
    console.log(props.myItemSt);
  };

  return (
    <View
      style={{
        flexDirection: "row"
      }}
    >
      <h3>{props.myItemTxt}</h3>
      <Button onPress={onBtPress} title="Learn More" />
      <h3>{props.myItemSt[props.myItemId]}</h3>
    </View>
  );
};

export default function App() {
  const [selectedOpt, setSelectedOpts] = useState(new Array(0));

  useEffect(() => {
    setSelectedOpts(new Array(myList.length).fill(0));
  }, []);

  const updateOptions = (ix: number) => {
    ++selectedOpt[ix];
    setSelectedOpts(selectedOpt);
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      {myList.map((itm, ix) => {
        return (
          <MyItem
            key={ix}
            myItemId={ix}
            myItemTxt={itm.cTx}
            myItemSt={selectedOpt}
            myItemClck={() => updateOptions(ix)}
          />
        );
      })}
    </div>
  );
}

提前一百万谢谢!

如果需要更多信息,请告诉我

【问题讨论】:

    标签: react-native react-props use-effect use-state react-state


    【解决方案1】:

    为了改变列表中的数据。你需要这样做

     const updateOptions = (ix: number) => {
        const newList = selectedOpt.map((m, i) => {
          if (i === ix) {
            return m + 1;
          }
          return m;
        });
        setSelectedOpts(newList);
      };
    
    

    【讨论】:

    • 感谢确实有效!与我的解决方案相比,您知道为什么它有效吗?因为我的似乎也更新了道具(参见 onBtpress() 上的道具检查)。
    • 我猜在你的解决方案中。数据没有更新。
    猜你喜欢
    • 2017-10-01
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 2021-09-20
    • 2020-10-20
    • 1970-01-01
    • 2021-08-06
    相关资源
    最近更新 更多