我正在尝试做一个单行条件语句以在React组件的state
内设置变量的值。
请查看下面的提取代码:
class ModuleInstance extends React.Component {
// Initial module counter
state = {
assignments: this.props.assignments,
params: [
{single_assigment: this.props.assigments.length === 1 ? true : false}
],
}
ModuleInstance从其父类接收assignments
作为传递的道具,但是,在尝试分配single_assigment
时,它无法识别道具并抛出*TypeError: Cannot read property 'length' of undefined*
。
请记住,我对Javascript开发还很陌生,但是如果有人可以解释这是怎么回事-我将不胜感激:)
答案 0 :(得分:1)
名称分配中有错字,g后面缺少n
class ModuleInstance extends React.Component {
// Initial module counter
state = {
assignments: this.props.assignments,
params: [
{single_assignment: this.props.assignments.length === 1 ? true : false}
],
}
答案 1 :(得分:1)
确保您通过了正确的this.props.assignments
,对this.props.assignments
进行了虚假检查,是的,纠正了错字。
class ModuleInstance extends React.Component {
// Initial module counter
state = {
assignments: this.props.assignments,
params: [
{ single_assigment: (this.props.assignments && this.props.assignments.length === 1) ? true : false }
],
}
}