[英]Should i pass react hooks as a value to Context Provider?
I need global variable users that is able to filtering out some users.我需要能够过滤掉一些用户的全局变量用户。 Using react hooks passed as a value leading to rerendering page many times.
使用作为值传递的反应挂钩会导致多次重新渲染页面。 Which solution is better and why?
哪种解决方案更好,为什么?
export const UsersProvider = props => {
const [user, setUser] = useState({
isLogged: false
});
return (
<UsersContext.Provider value={[filteredUsers, setFilteredUsers]}>
{props.children}
</UsersContext.Provider>
);
};
OR或者
class UserProvider extends React.Component {
constructor(props) {
super(props);
this.setUser = () => {
this.setState(state => {
return {user: "true"};
});
console.log(this.state.user);
};
// State also contains the updater function so it will
// be passed down into the context provider
this.state = {
user: false,
setUser: this.setUser
};
}
render() {
return (
<UserContext.Provider value={this.state}>
{this.props.children}
</UserContext.Provider>
);
}
}
You only need to add what you need to use in a consumer.您只需要添加您需要在消费者中使用的内容。 Personally I only supply a couple functions/values like this:
就我个人而言,我只提供如下几个函数/值:
export const UsersProvider = props => {
const [user, setUser] = useState({
isLogged: false
});
const props = {
filteredUsers,
setFilteredUsers
};
return (
<UsersContext.Provider {...props}>
{props.children}
</UsersContext.Provider>
);
};
But I'd only add the things you need elsewhere to the props object.但我只会将你需要的东西添加到道具 object 中。 I doubt you need everything on your current component's state elsewhere because if you do, you may have an organization problem.
我怀疑您是否需要其他地方当前组件的 state 上的所有内容,因为如果这样做,您可能会遇到组织问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.