I am writing this page for a website using react and redux. My problem is when I try to access the index of the array that I get from the store I get the undefined value. But logging the array as a whole return the array correctly the following image describes what I am trying to say: ![Line 15 : console.log(this.props.reference) Line 16: console.log(this.props.reference[0])]1
At line 16 I log the whole array which is mapped to my props, which gives the result as expected but when I log this.props.reference[0] I get undefined. Here is my code for reference:
//rootreducer
const initState = {
ref : []
}
const rootReducer = (state = initState, action) => {
if (action.type === 'ADD_REF') {
let updatedref = state.ref;
updatedref[state.ref.length] = action.reference;
return {
...state,
ref: updatedref
};
}
return state;
}
export default rootReducer;
//Navbar.js
import React from 'react';
import {Nav , Navbar , NavDropdown } from "react-bootstrap";
import logo from "./constants/logo.png"
import {connect} from 'react-redux';
class Navbarr extends React.Component {
state = {
}
handleonClick = (num) => {
// console.log(this.props.reference)
// console.log(this.props.reference[0]);
//this.props.reference[num].current.scrollintoView();
}
componentDidMount () {
console.log(this.props.reference);
console.log(this.props.reference[0]);
}
render() {
return (
<div>
<Navbar bg="dark" expand="lg">
<img src={logo} style={{padding: "15px" , width:"70px" , height: "70px"}}/>
<Navbar.Brand style={{color: "white"}}></Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="mr-auto">
<Nav.Link href="#home" style={{color: "white"}} onClick={this.handleonClick(0)} >About</Nav.Link>
<Nav.Link href="#home" style={{color: "white"}} >Interests</Nav.Link>
<Nav.Link href="#link" style={{color: "white"}}>Projects</Nav.Link>
<Nav.Link href="#link" style={{color: "white"}}>Experience</Nav.Link>
<Nav.Link href="#link" style={{color: "white"}}>Skills</Nav.Link>
</Nav>
</Navbar.Collapse>
</Navbar>
</div>
);
}
}
const mapStatetoProps = (state) => {
return {
reference: state.ref,
}
}
const mapDispatchtoProps = (dispatch) => {
return {
addaboutref: (reference) => {dispatch({type: 'ADD_REF', reference: reference})},
}
}
export default connect(mapStatetoProps,mapDispatchtoProps)(Navbarr);
console.log(JSON.stringify(this.props.reference))to see if the array has any elements? Your console messages will be updated as objects are updated (hover over the "i" icon in the console). This way, you can be sure that the console message shows thethis.props.referenceas it was when it mounted.