reactjs - 如何解决反应组件中变量的未定义值?
问题描述
我想解决获取“无法读取未定义的属性x”的错误
我想做什么?我有一个反应组件,在安装时我得到位置并将其作为道具发送给子组件......这样做我无法读取未定义的属性 x。
下面是我的代码,
export class ParentComponent extends React.PureComponent {
constructor(props) {
super(props);
}
componentDidMount() {
this.apply_position();
}
get_positioning = (rect, alignment) => {
switch(alignment) {
case 'left':
return {x: rect.left, y: rect.top + (rect.height / 2)};
case 'top':
return {x: rect.left + (rect.width / 2) , y: rect.top};
case 'bottom':
return {x: rect.left + (rect.width / 2), y: rect.bottom};
case 'right':
return {x: rect.right + (this.props.start_offset || 0), y:rect.top + (rect.height /
2)};
default:
return {x: (rect.left + rect.width / 2), y: rect.top + (rect.height / 2) +
(this.props.end_offset || 0)};
}
}
apply_position = () => {
const start_anchor_rect = this.props.start_anchor_element &&
this.props.start_anchor_element.getBoundingClientRect();
if (this.props.end_anchor_element) {
this.start_position = this.get_positioning(start_anchor_rect,
this.props.start_anchor_alignment);
const end_anchor_rect = this.props.end_anchor_element.getBoundingClientRect();
this.end_position = this.get_positioning(end_anchor_rect);
}
}
render() {
const {start_selector, end_selector, start_offset, end_offset, start_anchor_alignment} =
this.props;
return (
<ChildComponent
end_x={this.end_position.x}
end_y={this.end_position.y}
start_x={this.start_position.x}
start_y={this.start_position.y}
/>
);
}
}
我认为在第一次渲染时计算 end_position 或 start_position 的 x 值之前,它会出现此错误。我如何检查 start_position 和 end_position 是否有一些值然后渲染或类似的东西。有人可以帮我解决这个问题。谢谢。
解决方案
您没有存储start_position
and的计算end_position
。
您必须在构造函数中初始化它们。
constructor(props) {
super(props);
this.state = {
start_position: 0,
end_position: 0
}
}
使用React 的 api在你的get_positioning
函数中设置这些值。setState
然后您可以将它们用作this.state.start_position
和this.state.end_position
。
此外,您不会从apply_position
函数中返回。如果您不想使用状态并在作为 prop 传入时直接计算,则返回一个值<ChildComponent/>
您可以按以下方式执行上述操作:
apply_position = () => {
// ... exisiting computation of start_position and end_position.
return { start_position, end_position }
}
}
然后在您的渲染函数中,您可以检查从 apply_position 函数返回的值并在道具中使用它们。
render() {
let { start_position, end_position } = apply_position();
return (
<ChildComponent
end_x={end_position.x}
end_y={end_position.y}
start_x={start_position.x}
start_y={start_position.y}
/>
);
start_position
如果您的and中还有其他属性end_position
,那么您必须确保其中存在x
andy
属性。否则会抛出未定义的错误。
推荐阅读
- networking - Netty Server,同时需要是客户端
- selenium - 如何使用 selenium 查找包含在同一类下的所有文本
- wordpress - 如何从 Woocommerce 结帐页面隐藏产品信息?
- html - bootstrap 4中的水平滚动
- android - 如何停止跟踪位置?
- python - .isalpha 和 elif 是如何工作的?(Python)
- javascript - 随机调用 Img.onerror - SVG 字符串作为源
- firebase - Firebase Cloud Functions Express 应用退货声明
- javascript - 作为 Jest 测试的一部分,是否可以使资产 http 可获取
- pointers - XBee 开发板 LCD 显示屏上的字符显示