Console.log() Has A Value But When I Used It With Map Function It Became Undefined [reactjs]
Solution 1:
as error implies, this.state.allowedRoutes
is undefined, either after logging the value or on subsequent renders. you should also post your code too.
But for a workarround you can check not to be undefined
with this.state.allowedRouter && this.state.allowedRoutes.map()
As a side note, apparently you are updating your state in render method which is also not correct.
Solution 2:
It's likely that at some point you're updating your state and by mistake deleting allowedRoutes
. If you set your state without destructuring it first, all previous data will be removed, examples:
// WRONG - STATE BECOMES { allowedRoutes: myArray }this.setState({
allowedRoutes: myArray
});
// RIGHT - STATE BECOMES { all previous properties plus allowedRoutes: myArray }this.setState({
...this.state,
allowedRoutes: myArray
});
Also be sure to be initializing allowedRoutes as an empty array if you want to use map
without checking the value first (map
is an array method).
If you're using classes:
constructor(props) {
super(props);
this.state = {allowedRoutes: []};
}
If you're using hooks:
const [allowedRoutes, setAllowedRoutes] = useState([]);
Solution 3:
Your picture shows that the exception was thrown inside .map
:
this.state.allowedRoutes.map(
// the exception was thrown here
...
)
Please notice at this line, you can see allRoutes
is not defined in the current scope.
component={allRoutes[route.component]}
Post a Comment for "Console.log() Has A Value But When I Used It With Map Function It Became Undefined [reactjs]"