栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在渲染功能之外访问React Context

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在渲染功能之外访问React Context

编辑: 随着 v16.8.0中 引入react-hooks
,您可以通过使用

useContext
钩子在功能组件中使用上下文

const Users = () => {    const contextValue = useContext(UserContext);    // rest logic here}

编辑: 从版本 16.6.0 起。您可以通过使用上下文的生命周期的方法

this.context
一样

class Users extends React.Component {  componentDidMount() {    let value = this.context;      }  componentDidUpdate() {    let value = this.context;      }  componentWillUnmount() {    let value = this.context;      }  render() {    let value = this.context;      }}Users.contextType = UserContext; // This part is important to access context values

在版本16.6.0之前,您可以按以下方式进行操作

为了在您的生命周期方法中使用Context,您可以将组件编写为

class Users extends React.Component {  componentDidMount(){    this.props.getUsers();  }  render(){    const { users } = this.props;    return( <h1>Users</h1> <ul>   {users.map(user) => (     <li>{user.name}</li>   )} </ul>    )  }}export default props => ( <UserContext.Consumer>        {({users, getUsers}) => {return <Users {...props} users={users} getUsers={getUsers} />        }}      </UserContext.Consumer>)

通常,您将在您的应用程序中维护一个上下文,将上述登录名打包在HOC中以便重新使用是有意义的。你可以这样写

import UserContext from 'path/to/UserContext';const withUserContext = Component => {  return props => {    return (      <UserContext.Consumer>        {({users, getUsers}) => {          return <Component {...props} users={users} getUsers={getUsers} />;        }}      </UserContext.Consumer>    );  };};

然后你可以像这样使用它

export default withUserContext(User);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/409769.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号