【问题标题】:Reactjs new code not rendering to the browserReactjs 新代码未呈现到浏览器
【发布时间】:2018-03-25 13:46:57
【问题描述】:

我正在开发一个 React 应用程序,我不得不暂时停止工作。

我回来了。我使用 live-server public/

启动本地服务器

无论我在我的app.js 文件上做什么,都不会呈现任何内容。我仍然可以看到我在浏览器上所做的最后一项工作,但我的 app.js 文件对浏览器没有影响,即使浏览器上呈现的内容来自我的 app.js 文件。老实说,我永远无法习惯 React 这种无声的失败。所有文件都正常加载。

Stack Overflow 上的一位同事提供了一个有效的答案,即重做 package.json 安装,除了使用 npm 安装。

所以我跑了

npm init

npm install babel-preset-react babel-preset-env live-server重新安装

一切都恢复正常了。自从我处理这个应用程序以来已经有一段时间了,现在我又遇到了同样的问题。这次重做上述步骤不起作用。

这是我的 app.js 文件:

class DecisionTreeApp extends React.Component {
  constructor(props) {
    super(props);
    this.handleDeleteOptions = this.handleDeleteOptions.bind(this);
    this.handlePick = this.handlePick.bind(this);
    this.handleAddOption = this.handleAddOption.bind(this);
    this.state = {
      options: []
    };
  }
  handleDeleteOptions() {
    this.setState(() => {
      return {
        options: []
      };
    });
  }

  handlePick() {
    const randomNum = Math.floor(Math.random() * this.state.options.length);
    const option = this.state.options[randomNum];
    alert(option);
  }

  handleAddOption(option) {
    if (!option) {
      return 'Enter valid value to add item';
    } else if (this.state.options.indexOf(option) > -1) {
      return 'This option already exists';
    }

    this.setState((prevState) => {
      return {
        options: prevState.options.concat(option)
      };
    });
  }
  render() {
    const title = 'Decision Tree';
    const subtitle = 'For binary life decisions, put your trust in a computer';

    return (
      <div>
        <Header subtitle={subtitle} />
        <Action
          hasOptions={this.state.options.length > 0}
          handlePick={this.handlePick}
        />
        <Options
          options={this.state.options}
          handleDeleteOptions={this.handleDeleteOptions}
        />
        <AddOption handleAddOption={this.handleAddOption} />
      </div>
    );
  }
}

const Header = (props) => {
  return (
    <div>
      <h1>{props.title}</h1>
      <h2>{props.subtitle}</h2>
    </div>
  );
};

Header.defaultProps = {
  title: 'some default title'
};

const Action = (props) => {
  return (
    <div>
      <button
        onClick={props.handlePick}
        disabled={!props.hasOptions}
      >
        What should I do?
      </button>
    </div>
  );
};

const Options = (props) => {
  return (
    <div>
      <button onClick={props.handleDeleteOptions}>Remove All</button>
      {props.options.map(option => (
        <Option key={option} optionText={option} />
      ))}
    </div>
  );
};

const Option = (props) => {
  return (
    <div>
      {props.optionText}
    </div>
  )
};

class AddOption extends React.Component {
  constructor(props) {
    super(props);
    this.handleAddOption = this.handleAddOption.bind(this);
    this.state = {
      error: undefined
    };
  }
  handleAddOption(e) {
    e.preventDefault();

    const option = e.target.elements.option.value.trim();
    const error = this.props.handleAddOption(option);

    this.setState(() => {
      return { error };
    });
  }

  render() {
    return (
      <div>
        {this.state.error && <p>{this.state.error}</p>}
        <form onSubmit={this.handleAddOption}>
          <input type="text" name="option" />
          <button>Add Option</button>
        </form>
      </div>
    );
  }
}

ReactDOM.render(<DecisionTreeApp />, document.getElementById('app'));

这是我的文件结构:

这是我的/public/scripts/app.js

'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var DecisionTreeApp = function (_React$Component) {
  _inherits(DecisionTreeApp, _React$Component);

  function DecisionTreeApp(props) {
    _classCallCheck(this, DecisionTreeApp);

    var _this = _possibleConstructorReturn(this, (DecisionTreeApp.__proto__ || Object.getPrototypeOf(DecisionTreeApp)).call(this, props));

    _this.handleDeleteOptions = _this.handleDeleteOptions.bind(_this);
    _this.handlePick = _this.handlePick.bind(_this);
    _this.handleAddOption = _this.handleAddOption.bind(_this);
    _this.state = {
      options: []
    };
    return _this;
  }

  _createClass(DecisionTreeApp, [{
    key: 'handleDeleteOptions',
    value: function handleDeleteOptions() {
      this.setState(function () {
        return {
          options: []
        };
      });
    }
  }, {
    key: 'handlePick',
    value: function handlePick() {
      var randomNum = Math.floor(Math.random() * this.state.options.length);
      var option = this.state.options[randomNum];
      alert(option);
    }
  }, {
    key: 'handleAddOption',
    value: function handleAddOption(option) {
      if (!option) {
        return 'Enter valid value to add item';
      } else if (this.state.options.indexOf(option) > -1) {
        return 'This option already exists';
      }

      this.setState(function (prevState) {
        return {
          options: prevState.options.concat(option)
        };
      });
    }
  }, {
    key: 'render',
    value: function render() {
      var title = 'Decision Tree';
      var subtitle = 'For binary life decisions, put your trust in a computer';

      return React.createElement(
        'div',
        null,
        React.createElement(Header, { subtitle: subtitle }),
        React.createElement(Action, {
          hasOptions: this.state.options.length > 0,
          handlePick: this.handlePick
        }),
        React.createElement(Options, {
          options: this.state.options,
          handleDeleteOptions: this.handleDeleteOptions
        }),
        React.createElement(AddOption, { handleAddOption: this.handleAddOption })
      );
    }
  }]);

  return DecisionTreeApp;
}(React.Component);

var Header = function Header(props) {
  return React.createElement(
    'div',
    null,
    React.createElement(
      'h1',
      null,
      props.title
    ),
    React.createElement(
      'h2',
      null,
      props.subtitle
    )
  );
};

Header.defaultProps = {
  title: 'some default title'
};

var Action = function Action(props) {
  return React.createElement(
    'div',
    null,
    React.createElement(
      'button',
      {
        onClick: props.handlePick,
        disabled: !props.hasOptions
      },
      'What should I do?'
    )
  );
};

var Options = function Options(props) {
  return React.createElement(
    'div',
    null,
    React.createElement(
      'button',
      { onClick: props.handleDeleteOptions },
      'Remove All'
    ),
    props.options.map(function (option) {
      return React.createElement(Option, { key: option, optionText: option });
    })
  );
};

var Option = function Option(props) {
  return React.createElement(
    'div',
    null,
    props.optionText
  );
};

var AddOption = function (_React$Component2) {
  _inherits(AddOption, _React$Component2);

  function AddOption(props) {
    _classCallCheck(this, AddOption);

    var _this2 = _possibleConstructorReturn(this, (AddOption.__proto__ || Object.getPrototypeOf(AddOption)).call(this, props));

    _this2.handleAddOption = _this2.handleAddOption.bind(_this2);
    _this2.state = {
      error: undefined
    };
    return _this2;
  }

  _createClass(AddOption, [{
    key: 'handleAddOption',
    value: function handleAddOption(e) {
      e.preventDefault();

      var option = e.target.elements.option.value.trim();
      var error = this.props.handleAddOption(option);

      this.setState(function () {
        return { error: error };
      });
    }
  }, {
    key: 'render',
    value: function render() {
      return React.createElement(
        'div',
        null,
        this.state.error && React.createElement(
          'p',
          null,
          this.state.error
        ),
        React.createElement(
          'form',
          { onSubmit: this.handleAddOption },
          React.createElement('input', { type: 'text', name: 'option' }),
          React.createElement(
            'button',
            null,
            'Add Option'
          )
        )
      );
    }
  }]);

  return AddOption;
}(React.Component);

ReactDOM.render(React.createElement(DecisionTreeApp, null), document.getElementById('app'));

【问题讨论】:

  • 看起来这很可能是 live-serverwebpack (如果你甚至使用 webpack)问题,而不是 React 问题。您实际上可以很容易地将您的项目转移到create-react-app,这将解决您的构建/开发服务器问题。
  • @ShaneCavaliere,我没有使用webpack,我也开始怀疑live-server。有关如何将我的项目移至create-react-app 的任何文档?或者你的意思是在我的命令行中运行 create-react-app 并开始在那里重建它?
  • 是的,最简单的方法可能是在您的命令行中运行create-react-app,然后复制您的项目文件(CRA 查看src/index.js 以获得项目根目录)。如果只是那个 app.js 文件,重命名为 index.js 放到 src 文件夹中即可。
  • 对于小型项目,我还建议查看codeandbox.io。非常快速地将简单的 React 项目组合在一起而无需担心任何配置或设置,这真是太棒了。例如,我刚刚将您的代码复制到一个新的沙箱中,它工作正常:codesandbox.io/s/8plp6r942l。它也非常适合在 SO 上共享您的代码,让人们更容易查看它并帮助您解决问题。
  • @ShaneCavaliere,codesandbox.io 能否在需要将其部署到Heroku 时工作?这就是我最终想要做的。

标签: javascript reactjs


【解决方案1】:

Alejandra,根据您的设置,您的浏览器未呈现的原因是您需要使用 babel 转译您的代码,就像您的应用在 /public/scripts/app.js 中所做的那样。

为此,您需要在启动本地服务器时有两个可用的命令行终端。

live-server publicbabel src/app.js --out-file=public/scripts/app.js --presets=env,react --watch 在您编写代码时进行转译。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-22
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    • 1970-01-01
    • 2018-02-28
    • 1970-01-01
    相关资源
    最近更新 更多