“typeof QuestionInfo”类型的参数不可分配给“SetStateAction<QuestionInfo |未定义>'

时间:2021-07-21 04:32:46

标签: reactjs react-native react-redux react-hooks

I am getting response from server and create model class of QuestionInfo type. then I am assigning that object into state array. Now I am getting object from array. Code is given below.

        const [questions, setQuestions] = useState<[QuestionInfo] | undefined>();
        const [questionObj, setQuestionObj] = useState<QuestionInfo | undefined>()
    
    
       useEffect(() => {
            testAPICall();
        }, []);
    
    //Method Call
    const testAPICall = async () => {
            try {`enter code here`
                const response = await fetch("URL",
                    {`enter code here`
                        method: "get",
                        headers: {
                            "Authorization": "",
                        }
                    });
                const json = await response.json();
                console.log('Success :', json.data);
                setQuestions(json.data);
                setQuestionObj(questions[0])//This Line giving me error
    
            } catch (error) {
                console.error(error);
                console.log('error : ', error);
            } finally {
            }
        }
    }

我收到服务器的响应就像

"data": [
        {
            "question": {
                "en": "What are the 3 most important parts of the &quot;18 Months&quot; rule?"
            },
            "options": {
                "en": [
                    "Product, service & traction",
                    "Working capital, customer base & strategy",
                    "Product, service & failure",
                    "Service, working capital & strategy"
                ]
            },
            "_id": "ZZZZZZZ",
            "question_type": "single"
        },
        {
            "question": {
                "en": "what is the most important thing he should keep in mind?"
            },
            "options": {
                "en": [
                    "Product specifications",
                    "Brand strategy",
                    "Customer's problems",
                    "Working capital"
                ]
            },
            "_id": "YYYYYYY",
            "question_type": "single"
        }
    ],
    "id": "XXXXXXXXXXX"
}

我将每个对象存储在 QuestionInfo 对象中。如果我正在获取特定对象的对象。然后。我收到错误

我收到类似“'typeof QuestionInfo'类型的参数不能分配给'SetStateAction'类型的参数”之类的错误。

1 个答案:

答案 0 :(得分:0)

错误告诉您不能设置分配问题信息 |未定义类型到您的状态。

你有两个解决方案。

  1. 确保您在状态中保存的对象已定义,例如:
if (questions[0]) {
    setQuestionObj(questions[0])
}
  1. 在您的状态中添加未定义的类型:
const [questionObj, setQuestionObj] = useState<QuestionInfo | undefined>(