I have 3 components, TypeList , ConnectedType ( =connect(mapStateToProps)(Type
), and Type . Type will receive props from both TypeList ( onClick, name
) passing props to ConnectedType as well as ConnectedType's mapStateToProps ( onMiniPokemonClick, miniPokemon
). How do I do a check to see if miniPokemon
exists before mapping it out? Is it possible to do logic on a functional component or do I have to make it a class and create a helper function inside?
const Type = ({onClick, name, onMiniPokemonClick, miniPokemon}) => (
<li
onClick={onClick}
>
{name}
<ul>
{
if (miniPokemon) {
miniPokemon.map(function (pokemon, idx) {
return (<MiniPokemon onClick={() => onMiniPokemonClick(pokemon.name)} name={pokemon.name}/>)
})
}
}
</ul>
</li>
)
All you need to do is use brackets to allow a multiline function body
const Type = ({onClick, name, onMiniPokemonClick, miniPokemon}) => {
// some logic
return (
<li
onClick={onClick}
>...
</li>
)
}
Or if you just need to ensure that miniPokemon
is an array when a null/undefined value comes through - you could supply a default argument:
({onClick, name, onMiniPokemonClick, miniPokemon = []})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.