Reactjs 父道具更改时,平面列表项目不会重新排序
我有一个组件,它有一个平面列表,并且道具从父级传递到其中,如下所示 父组件Reactjs 父道具更改时,平面列表项目不会重新排序,reactjs,react-native,Reactjs,React Native,我有一个组件,它有一个平面列表,并且道具从父级传递到其中,如下所示 父组件 const Parent=(道具)=>{ 常数[currentValue,setCurrentValue]=使用状态(0); //此处检测到更改 console.log(当前值) 返回( ); }; FlatListContainer组件 constflatlistcontainer=(道具)=>{ const{currentValue,setCurrentValue}=props; 返回( `${item.id}`}
const Parent=(道具)=>{
常数[currentValue,setCurrentValue]=使用状态(0);
//此处检测到更改
console.log(当前值)
返回(
);
};
FlatListContainer组件
constflatlistcontainer=(道具)=>{
const{currentValue,setCurrentValue}=props;
返回(
`${item.id}`}
renderItem={({item,index})=>(
)
}
/>
);
};
为了简单起见,我没有包括如何检索数据
选择权如下
Optionite组分
const OptionItem=(道具)=>{
const{label,onPress,value,currentValue}=props;
const_onPress=()=>{
onPress(值);
};
返回(
{/*此处的内容*/}
{label}
{value==当前值?'Selected':'notselected'}
);
};
当我在OptionItem组件中输入console.log(currentValue)时,我在单击时没有看到值的变化。
如何在FlatListContainer和父组件中检测到更改
如何使OptionItem组件检测到此更改并相应地更改其内容将
extraData={currentValue}
添加到平面列表中。Flatlist仅在数据更改或外部数据更改时重新呈现
外部数据
用于通知列表重新呈现的标记属性(因为它实现了PureComponent)。如果您的renderItem、Header、Footer等函数依赖于data prop之外的任何内容,请将其粘贴在此处并进行不变的处理
const Parent = (props) => {
const [currentValue, setCurrentValue] = useState(0);
// Changes are detected here
console.log(currentValue)
return (
<FlatListContainer
currentValue={currentValue}
setCurrentValue={setCurrentValue}
/>
);
};
const FlatListContainer = (props) => {
const { currentValue, setCurrentValue } = props;
return (
<FlatList
data={data}
keyExtractor={item => `${item.id}`}
renderItem={({ item, index }) => (
<OptionItem
label={item.name}
value={item.id}
currentValue={currentValue}
onPress={setCurrentValue}
/>
)
}
/>
);
};
const OptionItem = (props) => {
const { label, onPress, value, currentValue } = props;
const _onPress = () => {
onPress(value);
};
return (
<TouchableOpacity
activeOpacity={0.6}
onPress={_onPress}
>
{/* CONTENT HERE */}
<Text>{label}</Text>
{value === currentValue ? 'Selected' : 'Not Selected'}
</TouchableOpacity>
);
};