简体   繁体   English

如何使用 useState 挂钩在 FormDataConsumer 中设置值

[英]How to use useState hook to set value within FormDataConsumer

I am having to set a const value using useState hook in FormDataConsumer .我必须使用FormDataConsumer中的useState挂钩设置一个 const 值。 This is necessary because the value of the const can only be gotten within FormDataConsumer .这是必要的,因为 const 的值只能在FormDataConsumer中获取。 This const value will be used as a prop to another component.此 const 值将用作另一个组件的道具。 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 .当组件在componentWillUpdatecomponentDidUpdate中重复调用setState时,可能会发生这种情况。 React limits the number of nested updates to prevent infinite loops. React 限制了嵌套更新的数量以防止无限循环。

//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.您得到的错误是因为 React 本身的工作方式 - 您更新了 state 变量,该变量使组件重新渲染,并且在每次渲染时您再次设置 state ......所以您最终陷入了无限循环。

To escape it you should either set a condition upon which the state will be updated eg要逃避它,您应该设置一个条件,在该条件下 state 将被更新,例如

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.或者使用引用通过useRef钩子更新它的当前属性来保存结果,因为此操作不会触发重新渲染。

const outletsListRef = useRef();

... 

outletsListRef.current = s;

Although not sure why you would need to save it and not rerender the component.虽然不确定为什么需要保存它而不是重新渲染组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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