【问题标题】:Warn: State updates from the useState() and useReducer() Hooks don't support the " + ... MERN Stack Application警告:来自 useState() 和 useReducer() Hooks 的状态更新不支持 " + ... MERN 堆栈应用程序
【发布时间】:2022-03-15 21:55:52
【问题描述】:

为什么我的 setUser 在我 console.log 时返回该警告? :

function dispatchAction(fiber, queue, action) {
  {
    if (typeof arguments[3] === 'function') {
      error("State updates from the useState() and useReducer() Hooks don't support the " + 'second callback argument. To execute a side effect after ' + 'rendering, declare it in the component body with useEffect().');
    }
  }

函数如下:

const UserContextProvider = (props) => {
    const [user, setUser] = useState({})
    
    useEffect(() => {
        fetch(`${API}/auth/user`, {
            method: 'GET',
            withCredentials: true,
            credentials: 'include'
        })
        .then (response => response.json())
        .then (response => {
            setUser(response.user)
            console.log(setUser)
        })
        .catch (error => {
            console.error (error);
        });
    }, [setUser])

注意:response.user 只是一个对象。而且我可以访问用户中的数据,而子组件中没有问题。

【问题讨论】:

    标签: node.js reactjs mongodb express mern


    【解决方案1】:

    我也遇到了这个问题;就我而言,这是因为我没有在子组件中声明所有传递的上下文。例如,在我的提供者中,我有:

    <Outlet context={[user, setUser, filter, setFilter]} />
    

    但我只是在我的子组件中声明内容状态:

    const [user, filter] = useOutletContext();
    

    所以它认为filter 状态是user 的设置器。我将其更改为包含所有传递的上下文:

    const [user, setUser, filter, setFilter] = useOutletContext();
    

    而且效果很好。

    【讨论】:

      猜你喜欢
      • 2019-10-23
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-17
      • 2020-05-12
      • 1970-01-01
      相关资源
      最近更新 更多