父项道具更改时FlatList项目不会重新呈现

时间:2019-09-27 05:10:35

标签: reactjs react-native

我有一个具有FlatList的组件,并且道具从父对象传递到它的方式如下。

父项

const Parent = (props) => {
  const [currentValue, setCurrentValue] = useState(0);
  // Changes are detected here
  console.log(currentValue)
  return (
    <FlatListContainer
      currentValue={currentValue}
      setCurrentValue={setCurrentValue}
    />
  );
};

FlatListContainer组件

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

为简单起见,我没有包括如何检索数据。

OptionItem如下。

OptionItem组件

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

当我在OptionItem组件内使用console.log(currentValue)时,单击时看不到值的变化。 如何在FlatListContainer和父组件中检测到更改。

我如何使OptionItem组件检测到此更改并相应地更改其内容

1 个答案:

答案 0 :(得分:1)

extraData={currentValue}添加到清单中。 Flatlist仅在数据更改或ExtraData更改中重新呈现。

extraData

一个标记属性,用于告诉列表重新呈现(因为它实现了PureComponent)。如果您的renderItem,Header,Footer等函数中的任何一个都依赖于数据道具之外的任何东西,请将其粘贴在这里并一成不变地对待。

https://facebook.github.io/react-native/docs/flatlist.html#extraData

相关问题