【问题标题】:useState getting confused when using multiple components使用多个组件时 useState 会感到困惑
【发布时间】:2019-08-26 19:29:04
【问题描述】:

在功能组件中更新状态所采取的操作错误地更新了最终加载组件的状态。

我已经将我正在做的事情简化为非常简单的代码。我想知道我是否遗漏了为什么这不起作用

这是循环创建子组件的父组件。

         {scoreDays.length >0 ? scoreDays.map((el,idx) =>(
          <ScoringDay key={idx} date ={el.day} score={el.score} 
            channels={el.channels} />
            )) : null}

这是 ScoringDay 组件。我只是使用按钮来更新状态中的文本并显示它。

         const ScoringDay = props => {
        [expanded, setExpanded] = useState(false);
        [test, setTest] = useState('starting text');

       return(
    <View>
    <Text>
        {test}
        </Text>
        <Text onPress={() =>setTest('Clicked here')}>Update value</Text>
    </View>
        )

在我的示例中,屏幕上显示了 3 个“ScoringDay”组件。但是,无论我单击哪个文本“更新值”,它总是会更新最后一个组件上的文本。

为什么没有将操作应用于正确的组件?我在键上使用索引...但不确定这里还需要更改什么?

【问题讨论】:

  • 您的密钥似乎有问题。您似乎使用 .map 索引作为键,如果数组元素始终位于同一位置,这应该没问题;是这样吗?您可以尝试为每个设置一个唯一的 id 并将其用于 key 吗?

标签: react-native react-hooks


【解决方案1】:

运行从父级到子级的状态更改。

      [testtext, setTestText] = useState('starting text');
...
        {scoreDays.length >0 ? scoreDays.map((el,idx) =>(
          <ScoringDay key={idx} date ={el.day} score={el.score} 
            channels={el.channels} testtext={testtext} setTestText={setTestText} />
            )) : null}

二手

         const ScoringDay = props => {
        [expanded, setExpanded] = useState(false);
        const { testtext, setTestText} = props
       return(
    <View>
    <Text>
        {testtext}
        </Text>
        <Text onPress={() =>setTestText('Clicked here')}>Update value</Text>
    </View>
        )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    • 1970-01-01
    • 2017-09-21
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多