开发者问题收集

TypeError:未定义不是对象(评估'items.map')[重复]

2022-08-26
6528

收到物品后,出现以下错误。 目前我只是在学习,并查看了有关此主题的其他答案,但没有任何结果。

export default function App() {
  const [items, setItems] = React.useState();

  React.useEffect(() => {
    axios
      .get('https://62fa26ddffd7197707e66da8.mockapi.io/items')
      .then(({ data }) => {
        setItems(data);
      })
      .catch((err) => {
        console.log(err);
        Alert.alert('Ошибка', 'Ошибка при получении статей');
      });
  }, []);

  return (
    <View>
      <StatusBar style="inverted" />
      {items.map((obj) => (
        <Post title={obj.title} price={obj.price} imageUrl={obj.imageUrl} />
      ))}
    </View>
  );
}

错误:

ERROR  TypeError: undefined is not an object (evaluating 'items.map')

This error is located at:
    in App (created by ExpoRoot)
    in ExpoRoot
    in RCTView (created by View)
    in View (created by AppContainer)
    in RCTView (created by View)
    in View (created by AppContainer)
    in AppContainer
    in main(RootComponent)
2个回答

items 默认值不是数组,只需设置空白数组为默认值即可。

const [items, setItems] = React.useState([]);
Ravi
2022-08-26

请不要忘记,首次渲染将使用 useState 中的默认状态。因此,您需要在 useState 中编写条件或传递有效的默认值(例如空数组)

Rusty Nail
2022-08-26