score:148
You have to add a condition in your componentDidUpdate
method.
The example is using fast-deep-equal
to compare the objects.
import equal from 'fast-deep-equal'
...
constructor(){
this.updateUser = this.updateUser.bind(this);
}
componentDidMount() {
this.updateUser();
}
componentDidUpdate(prevProps) {
if(!equal(this.props.user, prevProps.user)) // Check if it's a new user, you can also use some unique property, like the ID (this.props.user.id !== prevProps.user.id)
{
this.updateUser();
}
}
updateUser() {
if (this.props.isManager) {
this.props.dispatch(actions.fetchAllSites())
} else {
const currentUserId = this.props.user.get('id')
this.props.dispatch(actions.fetchUsersSites(currentUserId))
}
}
Using Hooks (React 16.8.0+)
import React, { useEffect } from 'react';
const SitesTableContainer = ({
user,
isManager,
dispatch,
sites,
}) => {
useEffect(() => {
if(isManager) {
dispatch(actions.fetchAllSites())
} else {
const currentUserId = user.get('id')
dispatch(actions.fetchUsersSites(currentUserId))
}
}, [user]);
return (
return <SitesTable sites={sites}/>
)
}
If the prop you are comparing is an object or an array, you should use useDeepCompareEffect
instead of useEffect
.
score:0
You could use the getDerivedStateFromProps()
lifecyle method in the component that you want to be re-rendered, to set it's state based on an incoming change to the props
passed to the component. Updating the state will cause a re-render. It works like this:
static getDerivedStateFromProps(nextProps, prevState) {
return { myStateProperty: nextProps.myProp};
}
This will set the value for myStateProperty
in the component state to the value of myProp
, and the component will re-render.
Make sure you understand potential implications of using this approach. In particular, you need to avoid overwriting the state of your component unintentionally because the props
were updated in the parent component unexpectedly. You can perform checking logic if required by comparing the existing state (represented by prevState
), to any incoming props
value(s).
Only use an updated prop to update the state in cases where the value from props
is the source of truth for the state value. If that's the case, there may also be a simpler way to achieve what you need. See - You Probably Don't Need Derived State – React Blog.
score:1
A friendly method to use is the following, once prop updates it will automatically rerender component:
render {
let textWhenComponentUpdate = this.props.text
return (
<View>
<Text>{textWhenComponentUpdate}</Text>
</View>
)
}
score:4
componentWillReceiveProps(nextProps) { // your code here}
I think that is the event you need. componentWillReceiveProps
triggers whenever your component receive something through props. From there you can have your checking then do whatever you want to do.
score:4
I would recommend having a look at this answer of mine, and see if it is relevant to what you are doing. If I understand your real problem, it's that your just not using your async action correctly and updating the redux "store", which will automatically update your component with it's new props.
This section of your code:
componentDidMount() {
if (this.props.isManager) {
this.props.dispatch(actions.fetchAllSites())
} else {
const currentUserId = this.props.user.get('id')
this.props.dispatch(actions.fetchUsersSites(currentUserId))
}
}
Should not be triggering in a component, it should be handled after executing your first request.
Have a look at this example from redux-thunk:
function makeASandwichWithSecretSauce(forPerson) {
// Invert control!
// Return a function that accepts `dispatch` so we can dispatch later.
// Thunk middleware knows how to turn thunk async actions into actions.
return function (dispatch) {
return fetchSecretSauce().then(
sauce => dispatch(makeASandwich(forPerson, sauce)),
error => dispatch(apologize('The Sandwich Shop', forPerson, error))
);
};
}
You don't necessarily have to use redux-thunk, but it will help you reason about scenarios like this and write code to match.
score:22
You could use KEY
unique key (combination of the data) that changes with props, and that component will be rerendered with updated props.
score:47
componentWillReceiveProps()
is going to be deprecated in the future due to bugs and inconsistencies. An alternative solution for re-rendering a component on props change is to use componentDidUpdate()
and shouldComponentUpdate()
.
componentDidUpdate()
is called whenever the component updates AND if shouldComponentUpdate()
returns true (If shouldComponentUpdate()
is not defined it returns true
by default).
shouldComponentUpdate(nextProps){
return nextProps.changedProp !== this.state.changedProp;
}
componentDidUpdate(props){
// Desired operations: ex setting state
}
This same behavior can be accomplished using only the componentDidUpdate()
method by including the conditional statement inside of it.
componentDidUpdate(prevProps){
if(prevProps.changedProp !== this.props.changedProp){
this.setState({
changedProp: this.props.changedProp
});
}
}
If one attempts to set the state without a conditional or without defining shouldComponentUpdate()
the component will infinitely re-render
Source: stackoverflow.com
Related Query
- render react component when prop changes
- Re-render React component when prop changes
- React not rerendering the component when prop changes
- How to render component conditionally when leaf value of global state changes using react hooks
- React App class won't render when a child Component changes
- React child component does re-render when prop changes value
- React Router Dom & Firebase Auth: history.push changes url but does not render new component when called after firebase auth create account
- How to have React re-render a functional component when prop changes
- React: how to use setState and render component when prop changes
- how to reload component back to original state when a prop changes in react
- React hooks doesn't re render component when props changes
- Is it possible to render a react component only when a prop is initialized?
- React: why child component doesn't update when prop changes
- How to fetch data when a React component prop changes?
- React component render is called multiple times when pushing new URL
- Typing React components in Flow when passing a component as a prop
- How to pass the match when using render in Route component from react router (v4)
- How to re render parent component when anything changes in Child Component?
- Updating the react component state when a global variable changes
- React context doesn't transfer when using a component as prop
- How to stop re render child component when any state changed in react js?
- Access prop outside of class in React when calling Higher Order Component
- Why memory leak happend and render slowing down when I close and re-open react component (material-table)?
- Only render a react component when I on submit from a form
- React useEffect hook does not fire when prop dependency changes
- React component not rerendering when props changes
- Generic React TypeScript component with 'as' prop (able to render any valid dom node)
- When do i need to pass prop to constructor of a react component using super(props)?
- Re-render React Component when query string changes
- React - How do i force child components to re render when parent state component changes?
More Query from same tag
- How can i search from mongodb with onchange input field?
- React / Redux app dispatching an action inside settimeout
- How can I write write reloadable async code with Om + Figwheel + core.async?
- Modal dialog auth with react-router
- Async function returning empty array, and then the desired data - causing app to crash
- How to include username in firebase's 'createUserWithEmailAndPassword' authentication method
- How to avoid submitting in the form of react-bootstrap-validation when press the enter key
- Get component's height every time it renders
- Why doesn't useEffect hook work as expected?
- Different output when passing string by props and using a const value
- Date format and time zone JS
- Is it possible to only show half of a SVG icon?
- Paste from clipboard not working with React Native on iOS simulator
- How to add checkbox or radio button inside the map method in react component?
- Having trouble Jest testing ajax modules with axios
- Best method to keep track of a users progression through reading sections of text
- I have downloaded nodejs for react but when my powershell open to install external tools it gives error shown in the image:-
- Page not returning data using React-Redux
- Rendering only one child component after state change
- Error when trying to get info from current session user. "Too many re-renders. React limits the number of renders to prevent an infinite loop."
- React.js is losing focus with controlled form input
- With Axios.Get, You have provided an out-of-range value `value` for the select component
- React - props is not defined
- Rendering list from list of arrays
- Is it good practice to put functions inside useEffect?
- Simulating a Div Click on Enzyme and React
- env-cmd Error: Failed to find .env file at path
- Material UI V4.11.0 - Override Autocomplete nested styles
- How do I update state when a window variable changes in react
- Tests react component (context.router - undefined)