繁体   English   中英

Console.log() 有一个值,但是当我将它与 map 函数一起使用时,它变得未定义 [ReactJS]

[英]Console.log() has a value but when I used it with map function it became undefined [ReactJS]

我很新来反应。

你能帮帮我吗😭

我花了很多时间研究这个错误。 但我发现没有什么可以解决我的问题。

我使用console.log()它返回一个数组。

但是下一行,我on line 30它与.map()函数一起on line 30

它抛出一个错误。

TypeError: Cannot read property 'map' of undefined

这是我的render()函数

  render() {
    return (
      <div>
        {console.log("errrrrrrrrrrrrr",this.state.allowedRoutes)}
        {this.state.allowedRoutes.map(route => (
          <Route
            exact
            path={route.url}
            component={allRoutes[route.component]}
            key={route.url}
          />
        ))}
        {this.state.redirectRoutes.map(url => (
          <Redirect to={url} />
        ))}
      </div>
    );
  }

它记录了{console.log("errrrrrrrrrrrrr",this.state.allowedRoutes)}的值。

但它不能使用map()函数。

这是我的浏览器记录的内容。

errrrrrrrrrrrrr (8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

这是我的浏览器的错误:

一个错误

正如错误所暗示的那样, this.state.allowedRoutes是未定义的,无论是在记录值之后还是在后续渲染中。 你也应该发布你的代码。
但是对于解决方法,您可以使用this.state.allowedRouter && this.state.allowedRoutes.map()检查是否undefined

作为旁注,显然您正在更新渲染方法中的状态,这也不正确。

很可能在某个时候您正在更新您的状态并错误地删除了allowedRoutes 如果您在不先解构的情况下设置状态,则将删除所有先前的数据,例如:

// WRONG - STATE BECOMES { allowedRoutes: myArray }
this.setState({
  allowedRoutes: myArray
});

// RIGHT - STATE BECOMES { all previous properties plus allowedRoutes: myArray }
this.setState({
  ...this.state,
  allowedRoutes: myArray
});

如果您想使用map而不先检查值( map是一个数组方法),请确保将 allowedRoutes 初始化为空数组。

如果您正在使用类:

constructor(props) {
    super(props);
    this.state = {allowedRoutes: []};
}

如果您使用钩子:

const [allowedRoutes, setAllowedRoutes] = useState([]);

您的图片显示异常是在.map中引发的:

this.state.allowedRoutes.map(
  // the exception was thrown here
  ...
)

请注意这一行,您可以看到allRoutes未在当前范围内定义。

component={allRoutes[route.component]}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM