REACT NATIVE / 我的子组件不会重新渲染,尽管道具发生了变化



我在下面的代码中遇到了一个问题(此处为沙盒https://codesandbox.io/s/silly-rubin-9ghc5?fontsize=14&隐藏导航=1&主题=黑暗(,道具会发生变化,但不会相应地刷新组件。

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

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>
);
}

提前感谢!

如果需要进一步的信息,请告诉我

为了更改列表中的数据。你需要做这个

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

最新更新