如何管理或更新从低阶到高阶组件的状态?

问题描述 投票:0回答:1

我想从低阶组件更新功能组件的状态。然而,我在这方面一直没有成功。有时,React 状态管理让我感到困惑。

在我提供的代码示例中,当有人点击水果项目时,可以对其进行编辑。显然,React 不会触发

useEffect
钩子内的回调。也没有使用
_finishEdit
函数更新状态。

谢谢您的帮助!

以下是代码示例,也链接在Expo Snacks

import React, { useState } from 'react';
import { SafeAreaView, View, StyleSheet, Text, StatusBar, TouchableOpacity, Modal, TextInput, Pressable } from 'react-native';

const App = () => {
  const FRUITS = [{ name: 'Banana', }, { name: 'Pineapple', }, { name: 'Strawberry', }];
  const [data, setData] = useState(FRUITS);

  const _addNew = () => {
    const dataCpy = [...data];
    dataCpy.push({ name: 'Another item', });
    setData(dataCpy);
  };

  const _onEdit = (edit, ind) => {
    const dataCpy = [...data];
    dataCpy[ind] = {name: edit};
    setData(dataCpy);
  };

  return (
    <SafeAreaView style={styles.container}>
      { data.map((item: any, ind: number) => <Item title={item.name} key={ind} onEdit={_onEdit} />) }

      <Pressable style={styles.button} onPress={_addNew}>
        <Text style={styles.buttonTextLarge}> + Add new item</Text>
      </Pressable>
    </SafeAreaView>
  );
};

export default App;


const Item = ({ title, key, onEdit }: { title: string, key: number, onEdit: (edit: string, ind: number) => {} }) => {
  const [text, onTitleChanged] = React.useState(title);
  const [modalVisible, setModalVisible] = useState(false);

  React.useEffect(() => {
    onEdit(text, key);
  }, [text, onEdit, key]);

  const _toggleModal = () => {
    setModalVisible(!modalVisible);
  };

  const _onFinishEdit = () => {
    onEdit(text, key);
    _toggleModal();
  };

  return (<>
    <TouchableOpacity onPress={ _toggleModal }>
      <View style={styles.item}>
        <Text style={styles.title}>{title}</Text>
      </View>
    </TouchableOpacity>

    <Modal transparent={true} visible={modalVisible} onRequestClose={ _toggleModal }>
      <View style={styles.centeredView}>
        <View style={styles.modalView}>

          <TextInput
            style={styles.input}
            onChangeText={onTitleChanged}
            placeholder="useless placeholder"
            value={text}
          />

          <Pressable style={[styles.button, styles.buttonClose]} onPress={_onFinishEdit}>
            <Text style={styles.buttonText} >Finish edit</Text>
          </Pressable>

        </View>
      </View>
    </Modal>
  </>);

};


const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: StatusBar.currentHeight || 0,
    margin: 6,
  },
  item: {
    backgroundColor: '#00c2fe',
    padding: 12,
    borderRadius: 3,
    marginVertical: 8,
    marginHorizontal: 3,
  },
  title: {
    fontSize: 32,
  },
  input: {
    height: 40,
    margin: 12,
    borderWidth: 1,
    padding: 10,
  },
  centeredView: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 22,
  },
  modalView: {
    margin: 20,
    backgroundColor: 'white',
    borderRadius: 20,
    padding: 35,
    alignItems: 'center',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 4,
    elevation: 5,
  },
  button: {
    borderRadius: 3,
    padding: 9,
    elevation: 2,
    marginTop: 15,
    backgroundColor: '#5bddb9',
  },
  buttonClose: {
    backgroundColor: '#2196F3',
  },
  buttonText: {
    fontSize: 12,
    fontWeight: "bold",
  },
  buttonTextLarge: {
    fontSize: 24,
    fontWeight: "bold",
  },
});

reactjs react-hooks state
1个回答
0
投票

我已将问题发布到 ChatGPT。 以下是我得到的答案。

为了解决 React Native 代码中的问题,我们需要确保 onEdit 函数在编辑水果项时正确更新父组件的状态。需要进行一些调整才能使其正常工作:

  1. 将 ind 正确传递给 Item 组件:目前,您传递的 key 是 React 中的保留 prop,无法在组件内部访问。相反,显式传递 ind。
  2. 修复useEffect依赖:确保useEffect仅在必要时触发。它应该在文本更改时触发,而不是在 onEdit 或按键更改时触发,因为它们是稳定的。
  3. 在App中正确更新状态:确保onEdit函数正确更新父组件中的状态。
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.