【问题标题】:How to update a JSON object value when value is entered in React Native Input/TextInput在 React Native Input/TextInput 中输入值时如何更新 JSON 对象值
【发布时间】:2021-12-27 19:16:29
【问题描述】:

作为调查的一部分,我有一个供用户完成的问题列表,我将问题呈现在不同的组件中,这些组件都位于父文件中。我能够从状态中更新的子组件中获取每个值,但现在想要更新我在当前设置为 Null 的 JSON 对象中拥有的 Answer 字段。

这是我的 JSON 对象,名为 data

我需要访问每个问题并更新answer 字段。

我的父文件目前如下所示:

export default function SurveyScreen({navigation, route}) {
  const [childNameValue, setChildNameValue] = useState('');

const updateQuestion = (answer, type_index, question_index) => {
    console.log(answer);
  };

return (
<ScrollView style={styles.cardContainer}>
        <View>
          <Text style={styles.title}>Please fill out all questions below</Text>
        </View>
        <View>

          <BasicTextInput
            title="Child's full name"
            value={childNameValue}
            onChangeValue={newValue => setChildNameValue(newValue)}
            updateQuestion(newValue);
          />
       );
}

及子组件文件:

export default function BasicTextInput({title, onChangeValue, updateQuestion}) {
  return (
    <View style={styles.container}>
      <View style={styles.containerHeader}>
        <Text style={styles.questionTitle}>{title}</Text>
      </View>
      <View style={styles.answerContainer}>
        <TextInput
          style={styles.input}
          onChangeText={onChangeValue}
          updateQuestion={updateQuestion}
        />
        <View />
      </View>
    </View>
  );
}

我在我的父组件中得到了答案,并成功运行了 console.log(answer)。

我希望能够在运行 axios 请求提交之前更新 JSON 对象中的答案字段。

我认为在我的 updateQuestion 函数中运行一些类似的东西可能会起作用,但想知道最好的方法吗?

data.questions[type_index].questions[question_index].answer.answer = answer;

提前谢谢你!

【问题讨论】:

    标签: reactjs json react-native function state


    【解决方案1】:

    你当然可以改变你想要更新的字段。

    或者您可以使用 React 能够检测到的适当的不可变更新:

    // something like
    const replace = (arr, i, insert) => [...arr.slice(0, i), insert, ...arr.slice(i+1)];
    const updateDeepDeepAnswer = {
      ...data,
      questions: replace(data.questions, type_index, {
      ... data.questions[type_index],
      questions: replace(data.questions[type_index].questions, question_index, {
        ...data.questions[type_index].questions[question_index],
        answer: {
          ...data.questions[type_index].questions[question_index].answer,
          answer,
        },
      }),
    }),
    }
    

    这就是为什么我们在 React 状态下尽量保持数据简单的原因。

    我很想:

    1. 将问题集和问题存储在不同的状态切片上。因此,对答案字段的更新并不是深度更新。
    2. 单独存储答案及其问题 ID。然后将这些 questionId + answer 对象发送到您的 api 以保存在数据库中。

    【讨论】:

    • 感谢您的帮助,我最终更改了代码,以便通过数据映射并动态列出问题,然后将 updateQuestion 函数作为道具传递,但您的回答确实帮助了我!欣赏它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 2020-07-23
    • 2016-07-04
    相关资源
    最近更新 更多