【发布时间】:2022-10-09 15:30:13
【问题描述】:
在easy-peasy 中,useStoreState() 钩子在我们使用钩子访问存储 ES6 类实例的 store 字段时不会导致重新渲染。例如:
store.js
import { action, createStore } from "easy-peasy";
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const store = createStore({
person: new Person("Tom", "20"), // <-- Stores ES6 class instance
updatePersonName: action((state, payload) => {
state.person.name = payload;
})
});
export default store;
app.jsx:
import "./styles.css";
import { useStoreActions, useStoreState } from "easy-peasy";
import React from "react";
export default function App() {
const person = useStoreState((state) => state.person);
return (
<div className="App">
<p>{JSON.stringify(person)}</p>
<EditPerson />
</div>
);
}
function EditPerson() {
const person = useStoreState((state) => state.person);
const updatePersonName = useStoreActions(
(actions) => actions.updatePersonName
);
return (
<input
value={person.name}
onChange={(e) => updatePersonName(e.target.value)}
/>
);
}
如果我们尝试在输入框中输入内容,即使updatePersonName 动作被成功调度(见下面的截图),输入框的值仍然保持不变。 person 存储状态未成功更新,useStoreState() 挂钩不会导致重新渲染。
【问题讨论】:
标签: reactjs ecmascript-6 es6-class easy-peasy