React Context 未将类更新为值 [英] React Context not updating for class as value
问题描述
我有一个使用类实例作为上下文值的上下文.在我更新了类实例之后.这种变化不会反映在消费者身上.消费者仍然得到旧的类值.有人能指出我如何实现这一目标的方向吗?
//服务类类服务{名称 = "旧名称"函数更改名称(新名称){this.name = newName;}}//上下文提供者功能应用(){const 服务 = 新服务();返回 (<ServiceContext.Provider value={service}><首页/></ServiceContext.Provider>);}
然后我尝试在一个组件中更改此服务的名称属性.
import React, { useContext } from "react";const SomeComponent = () =>{const service = useContext(ServiceContext);const onClick = () =>{service.changeName('newName')console.log(service.name)//这里名字更新了}return <button onClick={onClick}>Change</h1>;};
并尝试从组件中获取更新的值.
//上下文消费者import React, { useContext } from "react";const MyComponent = () =>{const service = useContext(ServiceContext);返回 {service.name}
;};
但在另一个消费者中.service.name 没有得到更新.我可以知道这是为什么吗?
React 不是这样工作的,它不是真正的反应式",仅仅因为你改变了一个值并不意味着组件会重新渲染.
导致重新渲染的唯一方法是使用 React 的 API.
请参阅
I have a context that using a class instance as context value. After I updated the class instance. The change doesn't reflect in the consumer. Consumer still get the old class value. Can someone point me the direction of how to achieve this?
// Service class
class Service {
name = "oldName"
function changeName(newName){
this.name = newName;
}
}
//Context provider
function App() {
const service = new Service();
return (
<ServiceContext.Provider value={service}>
<Home />
</ServiceContext.Provider>
);
}
Then I try to change the name attribute of this service in one component.
import React, { useContext } from "react";
const SomeComponent = () => {
const service = useContext(ServiceContext);
const onClick = () => {
service.changeName('newName')
console.log(service.name) //here the name has updated
}
return <button onClick={onClick}>Change</h1>;
};
And try to get the updated value from the component.
//Context consumer
import React, { useContext } from "react";
const MyComponent = () => {
const service = useContext(ServiceContext);
return <h1>{service.name}</h1>;
};
but in another consumer. service.name didn't get update. May I know why is that?
That's not how React works, it is not a "real reactive", just because you changed a value it doesn't mean the component will re-render.
The only way to cause a re-render is to use React's API.
See Rendering a Component in docs.
class Service {
name = "oldName";
changeName(newName) {
this.name = newName;
}
}
const service = new Service();
// Provider
function App() {
const [, render] = useReducer(p => !p, false);
return (
<ServiceContext.Provider value={{ service, render }}>
<SomeComponent />
</ServiceContext.Provider>
);
}
// Usage
const SomeComponent = () => {
const { service, render } = useContext(ServiceContext);
const onClick = () => {
service.changeName("newName");
render();
};
return <button onClick={onClick}>{service.name}</button>;
};
这篇关于React Context 未将类更新为值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!