Reputation: 29
I'm learning react native. I didn't figure out this problem. I have been using functional component in my project. Here is i don't understand to convert class component state :
constructor(props) {
super(props)
this.state = {
center: { lat: 5.6219868, lng: -0.23223 },
locations: {},
users_online: [],
current_user: ''
}
}
/* this.setState((prevState, props) => {
let newState = { ...prevState };
newState.center = location;
newState.locations[`${prevState.current_user}`] = location;
return newState;
}); */ ==> I wan't to convert to functional component this state.
Thank you for answering.!
Upvotes: 0
Views: 400
Reputation: 1248
It's pretty simple, although I would suggest you to checkout hooks concepts in react.
const [data, setData] = useState({
center: { lat: 5.6219868, lng: -0.23223 },
locations: {},
users_online: [],
current_user: ''
});
//one way
setData((prevState) => ({
...prevState,
center = location;
locations[`${prevState.current_user}`] = location;
}));
//another way
const handleTextChange = (text,field) => {
setStates(prev => ({
...prev,
[field]: text,
}))
};;
Also, you can main 4 different states as well.
const [center, setCenter] = useState({ lat: 5.6219868, lng: -0.23223 });
const [locations, setLocations] = useState({});
const [usersOnline, setUsersOnline] = useState([]);
const [currentUser, setCurrentUser] = useState('');
Upvotes: 2
Reputation: 1609
This is kind of a broad question and I think you should follow any getting started with hooks tutorial to understand what's going on. Anyways, in your case, you will first need to change it into a function instead of a class, then specify the four states values you have using an useState for each. For the batched updates, wrap the state settings functions inside an unstable_batchedUpdates method to trigger a single rerender for multiple state updates. Keep in mind, that the last method is unstable and might change in the future, but that gets things done for now.
Upvotes: 1