使用 Immutable 更新 React 状态

Updating React state with Immutable

我正在尝试通过 Immutable 更新我的常规 React 状态,但遇到了一些问题。状态不是深度嵌套的,或者它不是从状态本身以外的任何东西嵌套的,例如 { "username" : "keyval" : null}}

这意味着我无法执行 username.update('keyval', something) 之类的操作,相反我需要另一种方法。这是一个相当简单的问题,我只是不知道该怎么做。这是我的 setState 的样子,我想做一个不可变的 setState 动作。

handleUpdatePassword(event) {
    event.persist()
    this.setState(({password}) => ({
      password: state.update('password', event.target.value)
      })
    );
  }

这是我在尝试时遇到的错误:

   handleUpdatePassword(event) {
        event.persist()
        this.setState({
          password: state.update('password', event.target.value)
          })
      }

此外,这有效,但我收到此错误:this.state.updater is not a function

handleUpdateUsername(event) {
    console.log(this.state)
    event.persist()
    this.setState({
      username: this.state.update('username', event.target.value)
      })
  }

您正在创建明确的对象。让 ImmutableJS 为你做。

class YourReactComp extends React.Component {
  constructor() {
    this.state = Immutable.Map({"username": ""});
  }
  handleUpdateUsername(event) {
    console.log(this.state)
    event.persist()
    this.setState(this.state.set("username", event.target.value));
  }
}

编辑

ImmutableMap.update(key, updater)使用回调设置值,这里要ImmutableMap.set(key, newValue)

state 应该是一个普通的 JavaScript 对象,您可以在 documentation.

中阅读

Note that state must be a plain JS object, and not an Immutable collection, because React's setState API expects an object literal and will merge it (Object.assign) with the previous state.

您的初始状态应如下所示

constructor(){
     ...
     this.state = {data: Map({ password: "", username: ""})}
}

之后,您将能够像这样更新数据

handleUpdatePassword(event) {
 this.setState(({data}) => ({
      data: data.update('password', password =>  event.target.value)
    }));
}