3 回答

TA貢獻(xiàn)1834條經(jīng)驗(yàn) 獲得超8個(gè)贊
隨著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;
/* perform a side-effect at mount using the value of UserContext */
}
componentDidUpdate() {
let value = this.context;
/* ... */
}
componentWillUnmount() {
let value = this.context;
/* ... */
}
render() {
let value = this.context;
/* render something based on the value of UserContext */
}
}
Users.contextType = UserContext; // This part is important to access context values
在版本16.6.0之前,您可以按以下方式進(jìn)行操作
為了在您的生命周期方法中使用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>
)
通常,您將在您的應(yīng)用程序中維護(hù)一個(gè)上下文,并且將以上登錄信息打包在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);

TA貢獻(xiàn)1993條經(jīng)驗(yàn) 獲得超6個(gè)贊
好的,我找到了一種有限制的方法。通過該with-context庫(kù),我設(shè)法將我的所有消費(fèi)者數(shù)據(jù)插入到我的組件道具中。
但是,要在同一個(gè)組件中插入多個(gè)使用方很復(fù)雜,您必須使用此庫(kù)創(chuàng)建混合使用方,這會(huì)使代碼不夠美觀且效率低下。
該庫(kù)的鏈接:https : //github.com/SunHuawei/with-context
編輯:實(shí)際上,您不需要使用提供的多上下文api,with-context實(shí)際上,您可以使用簡(jiǎn)單的api并為每個(gè)上下文創(chuàng)建一個(gè)裝飾器,如果您想在組件中使用多個(gè)消費(fèi)者,則只需在類上聲明所需的裝飾數(shù)!
添加回答
舉報(bào)