推入数组时,MobX不更新React视图

我的Store.js:

import { observable, useStrict, action } from 'mobx';

useStrict(true);

export const state = observable({

    contacts: []

});

export const actions = {

    addContact: action((firstName, lastName) => {
        state.contacts.push({
            id: Math.floor((Math.random() * 1000) + 1),
            firstName: firstName,
            lastName: lastName
        });
    })

};

我的index.js:

import React from 'react';
import { Provider } from 'mobx-react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { state, actions } from './Store';

ReactDOM.render(
    <Provider state={state} actions={actions}>
        <App />
    </Provider>,
    document.getElementById('root')
);
registerServiceWorker();

我的App.js:

import React, { Component } from 'react';
import ContactList from './components/ContactList';
import ContactAdder from './components/ContactAdder';
import { observer, inject } from 'mobx-react';

const App = inject('state', 'actions')(observer(class App extends Component {
  render() {
    return (
      <div>

        <h1>Contacts</h1>

        <ContactList
          contacts={this.props.state.contacts}
          onDelete={this.props.actions.removeContact}
        />

        <ContactAdder onAdd={this.props.actions.addContact} />

      </div>
    );
  }
}));

export default App;

最后是我的ContactAdder.js:

import React, { Component } from 'react';

class ContactAdder extends Component {

    render() {
        return (
            <div className='ContactAdder'>
                <input type='text' value='' placeholder='First Name' />
                <input type='text' value='' placeholder='Last Name' />
                <button onClick={this.props.onAdd.bind(this, 'Test', 'Testerson')}>Add</button>
            </div>
        );
    }

}

export default ContactAdder;

在Store.js中运行addContact()之后,当我执行控制台日志时,我可以看到该数组确实发生了变异.但是由于某种原因,我的观点没有反应.我究竟做错了什么?

解决方法:

如果没有看到您的ContactList组件,我认为如果您也将其设为观察者,则该问题将得到解决.

一旦在先前渲染中取消引用的可观察对象发生更改,观察者组件将重新渲染. this.props.state.contacts不会取消引用联系人数组.如果您编写了this.props.state.contacts.slice()或this.props.state.contacts.peek(),它会起作用,但是通常仅在passing observables to external libraries时使用.

您最好使所有使用可观察性的组件都成为观察者,以使其尽可能高效.

上一篇:《统计学习方法(李航)》讲义 第03章 k近邻法


下一篇:javascript – 为mobx功能添加去抖动