REACT 数组 True 或 False 输入?

REACT Array True or False Inputs?

我很难序列化我的输入并将其保存在我的 API 上。我无法让它发挥作用。 需要一些建议或输入如何使用数组或什至另一种更简单的方法来做到这一点。

我在如何将单选按钮输入数组数据放入将保存到我的 postData 中时遇到问题API

postData是questionid,questiontype和answers

问题:

1.Earth是平的吗?真假 2.Earth是圆的?对错

所以我的输入是这样的单选按钮

handleTF(event) {
 const tfc = event.target.value;
 console.log(event.target.name)
 console.log(tfc);
 this.setState({ [event.target.name]: tfc});
}

const tfcs = ["True", "False"]

{tfcs.map((tfc, index) => (
  <label key={index}>
     {tfc}
       <input
         name={qd.question.id} 
           value={tfc}
           onChange={this.handleTF}
           type="radio"
        />
   </label>
))}

handleSubmitTF(event){
        event.preventDefault();

        const {
            questionId,
            questionType,
            answer
        } = this.state;

        const postData = {

            questionId,
            questionType,
            answer,

        };

        let sessionToken = sessionStorage.getItem('session');
        let sessToken = sessionToken.replace(/\"/g, "");

        fetch('sample.net', {

        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': 'token'
        },
        body: JSON.stringify([postData]),
        })

        .then(response => response.json())
        .then(response => {
            console.log(response.title)
            if(response.title === "Error"){
                this.addNotification('danger', 'Danger', 'Already answered', 'top-right')
            }else{
                this.addNotification('success', 'Success', 'All Data is Saved', 'top-right')
                this.componentDidMount();
            }

        })      
        .catch(err => {

            console.log("fetch error" + err);
        });
    }

上下文

您的状态似乎由以下部分组成:

{ [event.target.name]: "True" | "False" }

但随后您可以通过以下方式访问它:

const {
    questionId,
    questionType,
    answer
} = this.state;

它们不匹配类型/接口。在 TypeScript 中,你的状态看起来像:

interface State {
  [k: string]: "True" | "False";
}

解决方案

一个。直接发送您的状态

由于它具有有效的结构,因此在 API 端很容易解析。

const postData = { ...this.state };

乙。发送一系列答案

否则,如果您需要它作为答案数组。您可以将其转换为:

const questions = Object.keys(this.state);

const postData = questions.map((question) => ({
  question,
  answer: this.state[name],
}));

旁注:地球是平的,叫做圆盘世界=o)