gpt4 book ai didi

reactjs - 为什么无论状态是对象还是字符串,React 都会以不同的方式重新呈现?

转载 作者:行者123 更新时间:2023-12-04 01:07:13 25 4
gpt4 key购买 nike

下面的 React 示例,userProfile 状态是一个对象:
第一次渲染:状态为 {}
第二次渲染:状态为 res.data
-> 无限重新渲染

如果 userProfile 更改为 string 例如useState('')setUserProfile(res.data.bio)
第一次渲染:状态为 ''
第二次渲染:状态为 res.data.bio
第三次渲染:状态为 res.data.bio
-> 在第 3 次

后停止重新渲染

两个问题:

  • 为什么 React 会根据 userProfile 状态是对象还是字符串来重新呈现不同的内容?
  • userProfile 是一个字符串时,为什么 React 在第 3 次渲染后而不是在第 2 次渲染后停止重新渲染?

App.js

import UserProfile from './UserProfile';

const App = () => {
const login = 'facebook';

return (
<Router>
<Link to={`/user/${login}`}>Fetch Facebook bio from GitHub</Link>
<Route path='/user/:login' component={UserProfile} />
</Router>
);
};

用户配置文件.js

const UserProfile = ({ match }) => {
const [userProfile, setUserProfile] = useState({});

const getUser = async username => {
const url = `https://api.github.com/users/${username}`;
const res = await axios.get(url);
setUserProfile(res.data);
};

getUser(match.params.login);
// intentionally not using useEffect(() => { getUser(match.params.login); }, []);

return (<p>{userProfile.bio}</p>);
};

最佳答案

React 检查状态变量是否已更改,如果已更改,则重新渲染。因为无论你比较两个对象多少次(即使它们看起来相同),它们总是不同的,React 将继续重新渲染。

另一方面,字符串是原始类型,因此比较不同。试试这个:

console.log({d: 3} === {d: 3})
console.log("sss" === "sss")

它会让您了解为什么会发生这种情况。

因此,即使您一直将状态变量设置为同一个对象,它也不完全相同。但是字符串是相同的,所以它停止重新呈现。

查看这篇关于 JS 中对象相等性的文章:http://adripofjavascript.com/blog/drips/object-equality-in-javascript.html

现在让我回答你的第二个问题:

When userProfile is a string, why does React stop re-rendering after the 3rd render instead of after the 2nd one?

如果您查看 React Docs ,你会遇到这两段,我相信这回答了你的问题:

If you update a State Hook to the same value as the current state,React will bail out without rendering the children or firing effects.(React uses the Object.is comparison algorithm.)

Note that React may still need to render that specific component again before bailing out. That shouldn’t be a concern because Reactwon’t unnecessarily go “deeper” into the tree. If you’re doingexpensive calculations while rendering, you can optimize them withuseMemo

注意第二段。

关于reactjs - 为什么无论状态是对象还是字符串,React 都会以不同的方式重新呈现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66057904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com