【问题标题】:How to update parent state array from child component?如何从子组件更新父状态数组?
【发布时间】:2019-06-03 10:12:42
【问题描述】:
App
|
|----|---------------------|
     |                     |
     RadioInputForm        TextInputForm

我正在尝试使用来自子组件的数据更新父状态中的数组,但事件未触发。我已经尝试过以前的解决方案,例如 {() => callback()} 和 {() => callback.bind(this)},但似乎没有任何效果。

在指定索引处输入值后,应更新处于父状态的数组。这将如何工作类似于调查网络应用程序,您应该能够返回到以前的条目,因此是数组。

这是我到目前为止所尝试的,任何帮助将不胜感激:

// App.js
constructor(props) {
    super(props);

    let radioQuestions = [], textQuestions = [];
    let option = {id: "", options: {option1: false, option2: false, option3: false}, text: ""};

    for(var i = 0; i < data.questions.length; ++i) {
        textQuestions[i] = "";

        if(data.questions[i].question_type === "RadioQuestion") {
            radioQuestions[i] = option;
            radioQuestions[i].id = data.questions[i].id;
        } else radioQuestions[i] = {};
    }

    this.state = {
        textQuestions: textQuestions,
        radioQuestions: radioQuestions,
        index: 0
    };

    this.handleRadioSelect= this.handleRadioSelect.bind(this);
    this.handleRadioTextChange = this.handleRadioTextChange.bind(this);
    this.handleTextQuestionChange= this.handleTextQuestionChange.bind(this);
    this.handleBack = this.handleBack.bind(this);
    this.handleNext = this.handleNext.bind(this);
}

handleRadioSelect(e) {
    const { value } = e.target;
    const questions = this.state.radioQuestions.slice();
    const index = this.state.index;

    switch(value) {
        case "option1":
            if(questions[index].options.option1 === true)
                questions[index].options.option1 = false;
            else questions[index].options.option1 = true;
            break;
        case "option2":
            if(questions[index].options.option2 === true)
                questions[index].options.option2 = false;
            else questions[index].options.option2 = true;
            break;
        case "option3":
            if(questions[index].options.option3 === true)
                questions[index].options.option3 = false;
            else questions[index].options.option3 = true;
            break;
        default:
    }

    this.setState({
        radioQuestions: questions
    });
}

handleRadioTextChange(e) {
    const { value } = e.target;

    const questions = this.state.radioQuestions.slice()
    questions[this.state.index].text = value;

    this.setState({
        radioQuestions: questions
    })
}

handleTextQuestionChange(e) {
    const { value } = e.target;

    const answers = this.state.textAnswers.slice()
    answers[this.props.index] = value;

    this.setState({
        textAnswers: answers
    })
}

带有 Radio 表单的子组件:

constructor(props) {
    super(props);

    this.state = {
        radioQuestions: this.props.radioQuestions
    }

    this.handleRadioTextChange = this.handleRadioTextChange.bind(this);
    this.handleRadioSelect = this.handleRadioSelect.bind(this);
}

handleRadioSelect(e) {
    const { value } = e.target;
    const questions = this.state.radioQuestions.slice();
    const index = this.state.index;

    console.log(JSON.stringify(questions[index]));

    switch(value) {
        case "option1":
            if(questions[index].options.option1 === true)
                questions[index].options.option1 = false;
            else questions[index].options.option1 = true;
            break;
        case "option2":
            if(questions[index].options.option2 === true)
                questions[index].options.option2 = false;
            else questions[index].options.option2 = true;
            break;
        case "option3":
            if(questions[index].options.option3 === true)
                questions[index].options.option3 = false;
            else questions[index].options.option3 = true;
            break;
        default:
    }

    this.props.handleRadioSelect(e);

    this.setState({
        radioQuestions: questions
    });
}

handleRadioTextChange(e) {
    const { value } = e.target;

    const questions = this.state.radioQuestions.slice()
    questions[this.props.index].text = value;

    this.setState({
        radioQuestions: questions
    })
}

render() {
    return (
        <div className="form-group">
            <input type="radio" name="option1"
                  value="option1"
                  onChange = { this.state.handleRadioSelect }
                  defaultChecked={ this.state.radioQuestions[this.props.index].options.option1 } /> Option 1<br />
            <input type="radio" name="option2"
                  value="option2"
                  onChange = { this.state.handleRadioSelect }
                  defaultChecked={ this.state.radioQuestions[this.props.index].options.option2 } /> Option 2<br />
            <input type="radio" name="option3"
                  value="option3"
                  onChange = { this.state.handleRadioSelect }
                  defaultChecked={ this.state.radioQuestions[this.props.index].options.option3 } /> Option 3<br />
            <textarea rows="1" cols="40" id="answer" name="answer"
                className ="form-control input-default"
                onChange={ this.state.handleRadioTextChange }
                defaultValue = { this.state.radioQuestions[this.props.index].text } />
        </div>
    );
}

重复代码(在父子代码中)来自我解决问题的尝试。最后是文本输入表单组件:

constructor(props) {
    super(props);

    this.state = {
        textAnswers: this.props.textQuestions,
    };

    this.handleTextQuestionChange = this.handleTextQuestionChange.bind(this);
}

handleTextQuestionChange(e) {
    const { value } = e.target;

    const answers = this.state.textAnswers.slice()
    answers[this.props.index] = value;

    this.props.handleTextQuestionChange(e);

    this.setState({
        textAnswers: answers
    })
}

render() {
    return (
        <div className="form-group">
            <textarea rows="4" cols="50" id="answer" name="answer"
                className ="form-control input-default" onChange = { this.state.handleTextQuestionChange  }
                defaultValue = { this.state.textAnswers[this.props.index] } />
        </div>
    );
}

如果我没有遵循良好的做法,如果我有任何额外的建议,我也将不胜感激,谢谢。

【问题讨论】:

  • 我想我看到了一个解决方案,而且看起来很简单,但是你可以制作一个 sn-p 或 CodePen 以使其更易于使用吗?
  • 另外,@Mark20,你能把App组件的render方法贴在这里吗?
  • @0xc14m1z 这是一个代码框链接:codesandbox.io/s/4x5x6oo054
  • 谢谢@Mark20,我分叉了codesandbox并正在处理它。希望你不介意一点重构:)

标签: reactjs react-native ecmascript-6


【解决方案1】:

简答和工作代码框:https://codesandbox.io/s/21q3j32qyy 为了搞清楚问题出在哪里,我重构了很多东西,去掉了重复的代码。

下面的长答案...

首先,回顾一下问题

我们有一个对象,它应该来自 API 或任何包含用户问题列表的对象,以及调查标题等附加信息。

现在,样本数据在App.js 中检索到:

var data = require("./payload.json");

合法,即使使用 ES6,也可以这样编写(为了与其余代码保持一致):

import data from "./payload.json"

查看payload.json文件,是否可以看到有3种可能的问题类型:

  1. 具有 3 个选项,其行为类似于复选框(即使在您的代码中它们是单选)和文本;
  2. 只有文字;
  3. 带有图片上传器;

问题还包含要提示给用户的文本、标识和区分它们的类型。

用户还应该能够浏览他/她的答案。

目标

在我看来,您基本上...需要此表单来工作并将用户的所有答案保持在状态(我想您应该在某个时间将它们发送到 API)。

App.js

这是应用程序的主要组件,或者至少是示例的主要组件。

这里我们应该:

  1. 接受/处理从某处检索到的问题;
  2. 呈现当前问题;
  3. 能够浏览问题;
  4. 处理用户的回答;

在您的构造函数中,您做了一些对我来说似乎很奇怪的事情(当然,如果由于某种原因它是正确的,请告诉我):您循环遍历数据变量中的每个问题并创建两个单独的数组,一个用于文本问题一个用于广播问题,当问题属于另一种类型时,保留两个虚假元素......

相反,我想创建一个独特的空答案数组,每种类型的问题都有不同的字段。所以我创建了一个Answers.js 文件来处理一些事情。

首先,我有用于保存各种类型问题的字段(及其默认值)的常量:

// Answers.js    

const RADIO_FIELDS = {
  options: {
    option1: false,
    option2: false,
    option3: false
  }
};

const TEXT_FIELDS = {
  text: ""
};

const UPLOAD_FIELDS = {
  file: "",
  imageUrl: ""
};

我还创建了另一个文件Question.js,我在其中定义了一些实用程序常量来处理数据中定义的问题类型:

// Question.js

export const RADIO_QUESTION_TYPE = "RadioQuestion";
export const TEXT_QUESTION_TYPE = "TextQuestion";
export const UPLOAD_QUESTION_TYPE = "FileUpload";

export const QuestionTypes = {
  RADIO: RADIO_QUESTION_TYPE,
  TEXT: TEXT_QUESTION_TYPE,
  UPLOAD: UPLOAD_QUESTION_TYPE
};

解决了实用程序,在Answers.js 文件中,我创建了一个方法,该方法从问题开始返回“答案模板”纯对象。为了得到结果,我只检查问题类型并将一些常见字段与问题类型的专用字段合并:

// Answers.js

const fromQuestion = question => {
  const baseAnswer = {
    id: question.id,
    type: question.question_type
  };

  switch (question.question_type) {
    case QuestionTypes.RADIO:
      return Object.assign({}, baseAnswer, RADIO_FIELDS, TEXT_FIELDS);
    case QuestionTypes.TEXT:
      return Object.assign({}, baseAnswer, TEXT_FIELDS);
    case QuestionTypes.UPLOAD:
      return Object.assign({}, baseAnswer, UPLOAD_FIELDS);
    default:
      return null;
  }
};

这里我决定处理未知类型的问题:在 switch 的默认情况下返回 null 将过滤掉这些问题的显示。

再一次,我写了一个超级小的实用方法来做这个检查:

// Answers.js

const isValid = answer => answer !== null;

最后,一个方法从所有问题映射到所有(有效的)“答案模板”,然后像普通对象一样导出(只是因为我喜欢我们将在 App.js 组件中得到的语法我们什么时候使用这个方法):

// Answers.js

const from = questions =>
  (questions || []).map(fromQuestion).filter(isValid);

export default {
  from
};

此时,我们可以在 App.js 中导入 Answers.js 并这样设置状态变量:

// App.js

...
import Answers from './Answers';

export default class App extends React.Component {
  state = {
    answers: Answers.from(data.questions),
    index: 0
  };

  ...

我们将把这个对象放在answers 属性中:

[
  {
    id: 2501,
    type: "RadioQuestion",
    options: {
      option1: false,
      option2: false,
      option3: false
    },
    text: ""
  }, {
    id: 2447,
    type: "TextQuestion",
    text: ""
  }, {
  ...

很好,我们有自己的数据结构和从原始数据中获取数据的简洁方法。

现在我们必须正确呈现一个问题。在您的代码中发生这种情况:

// App.js, render method

...

render() {

  const question = () => {
    switch (data.questions[this.state.index].question_type) {
      case "RadioQuestion":
        return (
          <RadioQuestion
            radioQuestion={this.state.radioQuestions[this.state.index]}
            handleRadio={this.handleRadio}
          />
        );
      case "TextQuestion":
        return (
          <TextQuestion
            textQuestion={this.state.textQuestions[this.state.index]}
            handleText={this.handleText}
          />
        );
      case "FileUpload":
        return <FileUpload index={this.state.index} />;
      default:
        return <h2>Unknown Question Format</h2>;
    }
  };

  return (

  ...
  </label>

  { question() }

  <div className="form-group input-margin-top">
  ...

您正在执行一个方法,该方法会生成一些要呈现的内容……它只不过是一个组件!

因此,要以 React 方式进行,在 Question.js 文件中,我定义了一个类似于您的问题组件:

// Question.js

const Question = ({ type, ...props }) => {
  switch (type) {
    case RADIO_QUESTION_TYPE:
      return <RadioQuestion {...props} />;
    case TEXT_QUESTION_TYPE:
      return <TextQuestion {...props} />;
    case UPLOAD_QUESTION_TYPE:
      return <FileUpload {...props} />;
    default:
      return <h1>Unknown Question Format</h1>;
  }
};

export default Question;

我解构了 type prop 并渲染了一个不同的组件,只是传递了所有其他的 props。

继续编辑(我害怕失去一切!)

【讨论】:

    【解决方案2】:

    我认为这里的主要问题是您的状态包含一个包含对象的数组,这些对象没有使用Array.slice 函数进行克隆。请注意,此函数只是对数组进行浅拷贝,以便其中的对象在状态转换之间保持不变。

    我建议使用ImmutableJS 来处理深层对象的状态突变。

    【讨论】:

      猜你喜欢
      • 2017-09-28
      • 1970-01-01
      • 1970-01-01
      • 2021-04-06
      • 2018-04-20
      • 2023-02-19
      • 2019-12-23
      • 2016-12-21
      相关资源
      最近更新 更多