【问题标题】:easy-peasy: useStoreState not working with ES6 class instanceseasy-peasy:useStoreState 不适用于 ES6 类实例
【发布时间】: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


    【解决方案1】:

    问题

    easy-peasy 是 Redux 的抽象,根据Redux's docs

    强烈建议您只放普通的可序列化对象、数组和原语进入您的商店。

    由于 ES6 类实例不被视为可序列化对象,easy-peasy 将面临问题,因为我们使用了意外的数据类型。

    解决方案

    将 ES6 类转换为纯 JavaScript 对象:

    store.js

    import { action, createStore } from "easy-peasy";
    
    const store = createStore({
      // Use a plain JS object here ?
      person: {
        name: "Tom",
        age: "20",
      },
      updatePersonName: action((state, payload) => {
        state.person.name = payload;
      })
    });
    
    export default store;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-25
      • 2017-05-23
      • 1970-01-01
      • 2015-12-09
      • 2016-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多