首先我们回忆一下React Context API的用法(生产者消费者模式)。
创建context对象:
// context初始值
const INITIAL_VALUE = ‘’;
const MyContext = React.createContext(INITIAL_VALUE);
划定context使用的范围,管理它的值:
function App() {
return (
<MyContext.Provider value=“context value”>
<ConsumeComponent />
</MyContext.Provider>
);
}
获取context的值:
function ConsumeComponent() {
return (
<MyContext.Consumer>
{contextValue => (
<div>
<MyComponent value={contextValue} />
<div>{contextValue}</div>
</div>
)}
</MyContext.Consumer>
);
}
可以看到,使用Hook之前,消费这个context API是使用render props的方式。那如果这个context是一个原始数据,并不是用来直接显示的时候,就需要繁琐的特殊处理(比如传入到下一层component处理),让人不免尴尬。
有了useContext hook之后,这就不再是个问题了。我们只需要修改消费者那一步:
function ConsumeComponent() {
const contextValue = useContext(MyContext);
return (
<div>
<MyComponent value={contextValue} />
<div>{contextValue}</div>
</div>
);
}
context的值可以直接赋值给变量,然后想处理或者渲染都可以。
本文详细介绍了React中Context API的使用方法,包括创建context对象、划定使用范围及获取值的过程。通过对比使用render props与useContext hook的方式,展示了useContext简化context值处理的优势。
1308

被折叠的 条评论
为什么被折叠?



