【发布时间】:2021-08-05 10:29:57
【问题描述】:
我有一个如下所示的类组件:
interface MyState {
x_array: number[]
y_array: number[]
order_graph_1: number
}
class ItemsContainerOld extends React.Component<MyProps, MyState> {
constructor(props: MyProps) {
super(props)
this.state = {
x_array: [],
y_array: [],
order_graph_1: 1,
}
}
addingCoordinate(coord: {x: number; y: number}) {
const new_x_array = this.state.x_array.concat(coord.x)
const new_y_array = this.state.y_array.concat(coord.y)
this.setState({
x_array: new_x_array,
y_array: new_y_array,
})
}
setOrders(orders: number[]) {
this.setState({
order: orders[0],
})
}
render() {
return (
<div
>
<div>
<div>
<DrawerOld
addCoord={this.addCoord.bind(this)}
resetCoords={this.resetCoords.bind(this)}
/>
</div>
<div style={{paddingLeft: '70px', paddingTop: '50px'}}>
<Initial
x={this.state.x_array}
y={this.state.y_array}
deg={this.state.order_graph_1}
color={this.color_graph_1}
/>
</div>
</div>
</div>
)
}
}
export default ItemsContainerOld
我把它改成了一个功能组件。但是,在使用功能组件时,在此组件内:
<Initial x={x_array} y={y_array}
我开始遇到类似的错误
TypeError: Cannot read property 'length' of undefined
如何确保正确的值到达该组件?这是一个codesandbox: https://codesandbox.io/s/infallible-thunder-xsbrm?file=/src/ItemsContainerNew.tsx
【问题讨论】:
-
你需要找出为什么你的变量是
undefined。我建议使用this article 中的提示开始。 -
还有哪一行导致错误?
-
if (props.x.length === 0 && props.y.length === 0) {在此处的Initial文件中。 codesandbox.io/s/infallible-thunder-xsbrm?file=/src/…@Code-Apprentice -
我认为这里的快速解决方法是将您的条件更改为
if (props.x && props.y) -
您在此处发布的代码没有
if (props.x.length === 0 && props.y.length === 0)。
标签: reactjs typescript jsx setstate react-functional-component