Here how i can change this code to functional component. If i try to change this to functional component in console data is keep on printing. how i can solve that error. Kindly provide solution for this.
import React, { Component } from "react";
import { connect } from "react-redux";
import { getUsers } from "../actions/exampleAction";
function Users (props) {
props.getUsers();
const { users } = props.users;
console.log(props.users);
return (
<div>
{users.length &&
users.map((user) => {
return (
<React.Fragment key={user.id}>
<h6> {user.first_name} </h6>
<p> {user.last_name} </p>
<p> {user.email}</p>
<p>
<img key={user.avatar} src={user.avatar} alt="avatar" />
</p>
</React.Fragment>
);
})}
</div>
);
}
const mapStateToProps = (state) => ({ users: state.users });
export default connect(mapStateToProps, { getUsers })(Users);
CodePudding user response:
Since, at the during the initial rendering of the component, props.getUsers()
is called, when it is changed, again the props changes and component is rendered.
That's why you get multiple console logs.
You can read about side effects and using hooks on Functional Components here.
import React, { useEffect } from "react";
import { connect } from "react-redux";
import { getUsers } from "../actions/exampleAction";
function Users(props) {
const { users } = props.users;
useEffect(() => {
props.getUsers();
}, []);
return (
<div>
{users.length &&
users.map((user) => {
return (
<React.Fragment key={user.id}>
<h6> {user.first_name} </h6>
<p> {user.last_name} </p>
<p> {user.email}</p>
<p>
<img key={user.avatar} src={user.avatar} alt="avatar" />
</p>
</React.Fragment>
);
})}
</div>
);
}
const mapStateToProps = (state) => ({ users: state.users });
export default connect(mapStateToProps, { getUsers })(Users);
CodePudding user response:
You can also use hook available from "react-redux
" instead of mapStateToProps
or mapDispatchToProps
as given below
And you don't need to pass getUsers
as props because you already import it at the top so you can directly use it without props.
So go through following code and improve your coding standard
import React, { useEffect } from "react";
import {useSelector} from 'react-redux'
import { getUsers } from "../actions/exampleAction";
function Users(props) {
const users = useSelector(state => state.users);
useEffect(() => {
getUsers();
}, []);
if(!users.length) return null;
const userData = users.map((user) => {
return (
<React.Fragment key={user.id}>
<h6> {user.first_name} </h6>
<p> {user.last_name} </p>
<p> {user.email}</p>
<p>
<img key={user.avatar} src={user.avatar} alt="avatar" />
</p>
</React.Fragment>
);
});
return (
<div>
{userData}
</div>
);
}
export default Users;