从 mob-x store 渲染数据

Rendering data from mob-x store

我正在尝试让我的 h1 标签包含我的 mob-x 商店中的 Offers: text display 0,因为 auto 数组为空,但 h1 标签不显示任何内容,整个应用程序 编译只有一个错误:

警告:道具类型失败:提供给 inject-CardCheck-with-Autoarray 类型的道具 Auto 无效,应为 string。 inject-CardCheck-with-Auto(由 Auto 创建)

我改成字符串了还是不行

为什么 h1 标签不呈现 0,我怎样才能让它工作?

我有这个 React 组件:

import React, { Component } from 'react';
import { inject, observer } from 'mobx-react';
import PropTypes from 'prop-types';
import './cardCheck.css';

@inject('Auto')
@observer
class CardCheck extends Component {
  render() {
    const { Auto } = this.props;

    return (
      <div>
        <div className="newsletter-container">
          <h1>Enter the ID of your card:</h1>
          <div className="center">
            <input type="number" />
            <input type="submit" value="Check" />
          </div>
        </div>
        <h1>Offers:{Auto.carCount}</h1>
      </div>
    );
  }
}

CardCheck.propTypes = {
  Auto: PropTypes.string
};

CardCheck.defaultProps = {
  Auto: []
};

export default CardCheck

这是我的 mobx 商店:

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

class Auto {
  @observable auto = [];

  @action
  addAuto(car) {
    this.auto.push(car);
  }

  @computed
  get carCount() {
    return this.auto.length;
  }
}

export { Auto };

这是我的提供商:

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'mobx-react';
import { Restaurants } from './stores/Restaurants';
import { Beauty } from './stores/Beauty';
import { Tech } from './stores/Tech';
import { Malls } from './stores/ClothesData';
import App from './App';
import { Auto } from './stores/Auto';

const restaurants = new Restaurants();
const beauty = new Beauty();
const tech = new Tech();
const mall = new Malls();
const auto = new Auto();

window.restaurants = restaurants;
window.beauty = beauty;
window.tech = tech;
window.mall = mall;
window.auto = auto;

ReactDOM.render(
  <Provider restaurants={restaurants} beauty={beauty} tech={tech} mall={mall} auto={auto}>
    <App />
  </Provider>,
  document.querySelector('.container')
);

你的代码有 3 个错误。

  1. 您的 propTypes 与您的 defaultProps 冲突。您将 Auto 指定为 字符串 ,而默认情况下将其设置为空 数组 。这就是您看到错误消息的原因。

  2. 如前所述,您需要在您的CardCheck class.

  3. 中将所有Auto改为auto
  4. 其实你的store既不是字符串也不是数组,它是一个包含数组的对象

修复所有错误后,class 在我看来应该是这样的。

@inject('auto')
@observer
class CardCheck extends Component {
  render() {
    const { auto } = this.props;

    return (
      <div>
        // ...
        <h1>Offers:{auto.carCount}</h1>
      </div>
    );
  }
}

CardCheck.propTypes = {
  auto: PropTypes.shape({
    carCount: PropTypes.number,
    // if needed, use PropTypes.observableArray of MobX to check auto.auto here
  }),
};

CardCheck.defaultProps = {
  auto: {
    carCount: 0,
  }
};

export default CardCheck;