gpt4 book ai didi

javascript - 为什么 setState throw 对象作为 React 子对象无效?

转载 作者:行者123 更新时间:2023-11-29 23:16:04 25 4
gpt4 key购买 nike

尝试使用 this.setState(...) 时出现错误

  state = {
results: {},
isFinished: false,
activeQuestion: 0,
answerState: null,
quiz: [],
loading: true
};

async componentDidMount() {
try {
const resp = await axios.get(`/quizes/${this.props.match.params.id}.json`);
const quiz = resp.data;
this.setState({
quiz,
loading: false
})
} catch (e) {
console.log(e);
}
}

我的服务器请求成功返回一个数组,但是当我试图将它的值设置为本地状态时我得到了错误:

Objects are not valid as a React child (found: object with keys {errorMessage, label, touched, valid, validation, value}). If you meant to render a collection of children, use an array instead. in span (at ActiveQuiz.js:9) in p (at ActiveQuiz.js:8) in div (at ActiveQuiz.js:7) in ActiveQuiz (at Quiz.js:109) in div (at Quiz.js:98) in div (at Quiz.js:97) in Quiz (created by Route) in Route (at App.js:16) in Switch (at App.js:13) in main (at Layout.js:37) in div (at Layout.js:24) in Layout (at App.js:12) in App (at src/index.js:10) in Router (created by BrowserRouter) in Brodetailuter (at src/index.js:9)

和细节:

  21 | const resp = await axios.get(`/quizes/${this.props.match.params.id}.json`);   
22 | const quiz = resp.data;
23 |
> 24 | this.setState({
25 | quiz,
26 | loading: false
27 | })

如果我记录 quiz 对象,我会在控制台中得到 [{}]。并且所有的底层组件都成功获得了 props。

  render() {
return (
<div className={classes.Quiz}>
<div className={classes.QuizWrapper}>
<h1>Please answere:</h1>
{
this.state.loading
? <Loader/>
: this.state.isFinished
? <FinishedQuiz
results={this.state.results}
quiz={this.state.quiz}
onRetry={this.onRetryHandler}
/>
: <ActiveQuiz
answers={this.state.quiz[this.state.activeQuestion].answers}
question={this.state.quiz[this.state.activeQuestion].question}
onAnswerClick={this.onAnswerClickHandler}
quizLength={this.state.quiz.length}
answerNumber={this.state.activeQuestion + 1}
state={this.state.answerState}
/>
}
</div>
</div>
)
}

我用调试器 Prop 检查了 ActiveQuiz 是否正确。

请帮我解决一下。为什么会发生这种情况以及如何解决?

更新 1

const ActiveQuiz = props => {
debugger
return (
<div className={classes.ActiveQuiz}>
<p className={classes.Question}>
<span>
<strong>{props.answerNumber}.</strong>&nbsp;
{props.question}
</span>

<small>{props.answerNumber} из { props.quizLength }</small>
</p>

<AnswersList
state={props.state}
answers={props.answers}
onAnswerClick={props.onAnswerClick}
/>
</div>
)
};

最佳答案

您的错误表明它遇到了一个对象,因此无法呈现输出。它还指出,错误发生在 <span> 行.由于您的 activeQuestion是一个 int .因此你的 answerNumber Prop 不应该有错。

我的猜测是,它与您的 props.question 的数据结构有关.也许您要渲染的是一个对象/嵌套对象,因此会抛出一个错误,表明它无效。

希望对您有所帮助:)

关于javascript - 为什么 setState throw 对象作为 React 子对象无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52733434/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com