渲染来自mob-x存储的数据

时间:2018-08-01 17:56:40

标签: reactjs mobx

我正在尝试将我的h1标签包含在mob-x存储中,显示包含“要约:”文本的0,因为 自动数组为空,但是h1标签不显示任何内容,整个应用 编译时只有一个错误:

警告:道具类型失败:提供给Auto的类型array的道具inject-CardCheck-with-Auto无效,预期string。     在Inject-CardCheck-with-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')
);

1 个答案:

答案 0 :(得分:0)

您的代码中有3个错误。

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

  2. 如上所述,您需要在CardCheck类中将所有Auto更改为auto

  3. 实际上,您的商店既不是字符串也不是数组,它是包含数组的对象

修复所有错误后,我认为该类应如下所示。

@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;