简体   繁体   中英

How to use useState hook to set value within FormDataConsumer

I am having to set a const value using useState hook in FormDataConsumer . This is necessary because the value of the const can only be gotten within FormDataConsumer . This const value will be used as a prop to another component. The problem I am having is the error message below. What is the best way to do this? Thanks in advance

Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate . React limits the number of nested updates to prevent infinite loops.

//const initialized here
    const [outletsList, setOutletsList] = useState([]);

 
//the place where the const must be set
   

                     <FormDataConsumer>
                      {({ formData, ...rest }) => {
                        //console.log(`formData: ${JSON.stringify(formData)}`)
                        //console.log(`rest: ${JSON.stringify(rest)}`)
        
                        let s = GetOutletsBySalesRep({
                          distributorkey: formData.distributorid,
                          salesrep: formData.salesrep,
                        });
        
                        **setOutletsList(s);**
                      }}
                    </FormDataConsumer>

The error you get is because of the way React itself works - you update a state variable which makes the component to rerender and on each render you set the state again... so you end up in an endless loop.

To escape it you should either set a condition upon which the state will be updated eg

if(outletsList.length === 0) setOutletsList(s);

Or use a reference to save the result through the useRef hook updating it's current property because this operation doesn't trigger a rerender.

const outletsListRef = useRef();

... 

outletsListRef.current = s;

Although not sure why you would need to save it and not rerender the component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM