使用多个组件时useState变得混乱

时间:2019-08-26 19:29:04

标签: react-native react-hooks

为更新功能组件中的状态而采取的措施是错误地更新了已加载的最终组件的状态。

我已经将我的工作简化为非常简单的代码。我想知道我是否缺少某些东西,为什么它不起作用

这是父组件,可以循环创建子组件。

         {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”组件。但是,无论我单击哪个文本“更新值”,它始终会更新最后一个组件上的文本。

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

enter image description here

1 个答案:

答案 0 :(得分:0)

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

      [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>
        )