【问题标题】:undefiend state passed into the Component传递给组件的未定义状态
【发布时间】: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

如何确保正确的值到达该组件?这是一个codesandboxhttps://codesandbox.io/s/infallible-thunder-xsbrm?file=/src/ItemsContainerNew.tsx

【问题讨论】:

  • 你需要找出为什么你的变量是undefined。我建议使用this article 中的提示开始。
  • 还有哪一行导致错误?
  • if (props.x.length === 0 &amp;&amp; props.y.length === 0) { 在此处的Initial 文件中。 codesandbox.io/s/infallible-thunder-xsbrm?file=/src/…@Code-Apprentice
  • 我认为这里的快速解决方法是将您的条件更改为if (props.x &amp;&amp; props.y)
  • 您在此处发布的代码没有if (props.x.length === 0 &amp;&amp; props.y.length === 0)

标签: reactjs typescript jsx setstate react-functional-component


【解决方案1】:

您可以随时检查该值是否未定义,例如:


    if(this.props.x.length===undefined){
      return;
    }

如果你愿意,你可以在那里使用一些默认值。

**这是方法,每次遇到这种情况时,您都必须设置一些条件作为解决方法或设置初始默认值。

这是我的沙盒:https://codesandbox.io/s/vigilant-perlman-rzwge?file=/src/Initial.tsx:932-973

你应该知道的反应生命周期:

更新代码,完全正常工作:https://codesandbox.io/s/goofy-microservice-mw5j6?file=/src/Initial.tsx

【讨论】:

  • 你试过这个吗:if(this.props.x.length===undefined){ return; } 你也应该在文件中提供你的功能组件代码..但是我的解决方案应该可以工作..
  • 这对我不起作用。我在 ItemsContainerNew.tsx 文件中的代码是功能组件codesandbox.io/s/infallible-thunder-xsbrm?file=/src/…
  • ItemsContainerNew.tsx 为空,请从隐身窗口查看
  • @Jbd 看看这个,它现在正在工作:codesandbox.io/s/goofy-microservice-mw5j6?file=/src/Initial.tsx ... 不要忘记检查答案是否已接受
  • 这给出了一个错误Cannot read property 'concat' of undefined。当我点击网格时,这不应该发生
【解决方案2】:

你可以通过改变来解决问题

if (props.x.length === 0 && props.y.length === 0)

if (!props.x && !props.y)

虽然这可能掩盖了一个更深层次的问题。最好弄清楚为什么props.xprops.yundefined

【讨论】:

  • 但这两个不是相反的东西吗?
  • @Jbd 是的,你是对的。添加! 来解决这个问题。
【解决方案3】:

你需要改进你的状态初始化。

尽量不要将值设置为type 'any',更准确地说,在初始化x_arrayy_array时可以使用

// Notice that not only the type has changed from "any" to "number[]",
// But the initial value is now an empty array, causing their initial values 
// (and types) to be arrays since their starting point.
// When initialization happens without a starting value like "useState()",
// The state receives the value "undefined" which causes the error.

const [x_array, setXarray] = useState<number[]>([]);
const [y_array, setYattay] = useState<number[]>([]);

【讨论】:

  • 我试过这样做,但它会给我同样的“未定义值”错误。目前,在这个沙箱中,我在 index.js 中使用 ItemsContainerOld。但我想使用 ItemsContainerNew(功能组件)。 codesandbox.io/s/infallible-thunder-xsbrm?file=/src/Initial.tsx
  • 虽然这是一个很好的做法,但它对修复 TypeError: Cannot read property 'length' of undefined 没有任何作用。
猜你喜欢
  • 2021-11-12
  • 2020-08-06
  • 2019-10-23
  • 1970-01-01
  • 2021-12-01
  • 2018-07-09
  • 1970-01-01
  • 2019-04-02
  • 2022-01-01
相关资源
最近更新 更多