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 do I make the Toast appear?
- Pressing enter while focused on input causes sibling button to fire
- how are things being passed to onClick function
- jsPDF Autotable Images Gray and Washed out When multiple images
- How do i implement a dropdown header in Material-ui in react?
- Handling routes after submitting form
- Display JSON array in react component
- React page refresh value get undefined
- react context weird data type errors
- Access components props which is returned from HOC - Jest with React
- ReferenceError: window is not defined in Next.js using npm clevertap-react
- fs.readFileSync is not a function Meteor, React
- Handle multiple Material UI checkboxes in React
- How to handle multiple components in a loop with React-Redux
- React/Redux reducer won't register error from promise
- react-testing-library - Screen vs Render queries
- bootstrap-select is used in multiple places in one page but only working for the first one
- Error Missing parameter. You must specify location. (How to addListener for nearbySearch )
- trying to pass a value from child component to the parent component in react js
- Module parse error when trying to load background image in a css element
- CSS positioning footer elements (wave image and content)
- How can i call this action from my saga generator function?
- Input element's value in react component is not getting re-rendered when the state changes
- React state updating but rendering late
- React - external links not working after deployment
- React container component's method test with jest
- HOC react redux firebase. (Error: Firebase storage is required to upload files)
- How to fetch data from api using map in reactjs?
- How can I make this modal close onMouseLeave in my Reactjs application, styled with Material UI
- Why CSS pulse animation is not working without any errors?