带钩的功能组件可产生"cannot read property map of undefined"



我做了一个经典组件和一个功能组件,它们都应该做同样的事情。 它们都从我的 API 中提取数据,然后应该将其映射到 Div。但是,这不适用于功能组件,我宁愿使用带有钩子的功能组件。

我也尝试使用"UseLayoutEffect"钩子。我知道这种情况正在发生,因为第一次加载组件时,Games 是未定义的,它试图映射未定义,但是在微小的延迟之后,API 调用完成,游戏现在是一个对象数组。但是,它已经尝试映射未定义。我有一个条件"游戏",如果未定义,它应该阻止它被映射,但由于某种原因它通过了这个条件。

经典组件(工作(:

class Player extends React.Component {
constructor(props) {
super(props);
this.state = {
games: [],
players: {},
};
}
componentDidMount() {
this.fetchData()
}
async fetchData() {
const id = window.location.pathname.split('/')[2];
const games = await axios(`/api/players/${id}`);
this.setState({ games: games.data });
}
render() {
return(
<div>
{this.state.games.map((game, i) => (
<div className="historyId" key={i}>{game.match_id}</div>
))}
</div>
);
}
}

功能组件(不工作(: 未捕获的类型错误:无法读取未定义的属性"映射" 在播放器(捆绑.js:1422(

const Player = (props) => {
let { id } = useParams();
const [games, setGames] = useState({});
useEffect(() => {
async function fetchData() {
const response = await axios(`/api/players/${id}`);
setGames(response);
}
fetchData();
}, []);
return (
<div className="historyContainer">
<h1>Match history here...</h1>
{games && games.data.map((game, i) => <div>{game.match_id}</div>)}
</div>
);
}

您正在检查games是否存在,但它具有默认值(空对象(,因此它将始终存在。您不会检查games.data是否存在 - 直到您的HTTP请求完成为止。

试试这个:

{games.data && games.data.map((game, i) => <div>{game.match_id}</div>)}

试试这个:

const Player = (props) => {
let { id } = useParams();
const [games, setGames] = useState([]);
useEffect(() => {
async function fetchData() {
const {data} = await axios(`/api/players/${id}`);
setGames(data);
}
fetchData();
}, []);
return (
<div className="historyContainer">
<h1>Match history here...</h1>
{games.map((game, i) => <div>{game.match_id}</div>)}
</div>
);
}

这对我有用:

const {products}=useContext(ProductContext);
const [product, setProduct]=useState();
const getProduct=()=>{
if(props.match.params.id){
const res=products;
const data= res.filter(p=>{
return p.id === props.match.params.id;
})
setProduct(data); 
}
} 
useEffect(() => {
getProduct()
},[])
return (
<div>
{product && product.map(items=>(
<div key={items.id}>
<h2>{items.name}</h2>
</div>

))}
</div>
)

}

相关内容

最新更新