【问题标题】:Routing with Express when using React使用 React 时使用 Express 进行路由
【发布时间】:2018-04-29 05:59:12
【问题描述】:

我想使用 Express 为我的网络应用程序设置路由,并且我还使用 React 来处理前端。问题是我不明白在使用 React 组件时如何正确路由。

我的 index.html 中有:

<script> document.getElementById("input").onchange = function() {  ...  } </script>

还有我的 App.js:

class App extends Component {
    render() {
        return ( <div><input id="input" /></div> );
    }

}

还有 router.js:

app.get('/', function (req, res) {
    res.sendFile(path.resolve('public/index.html'))
})
app.use(express.static('static'));
app.listen(3001, function () {
  console.log('Example app listening on port 3001!')
})

还有静态/index.js:

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

问题是我收到“无法设置属性 'onchange' of null”。显然 App 对象没有被渲染,但我不明白为什么。我怎样才能做到这一点?

【问题讨论】:

  • 可以将您的脚本代码包装在传递给window.onload的函数中
  • 页面加载后,document.getElementById("input")在浏览器控制台返回什么?

标签: javascript html reactjs express


【解决方案1】:

我相信你需要快速路由器

Differences between express.Router and app.get?

var express = require('express');
var path = require('path');
var router = express.Router();

router.get('/', function(req, res) {
    res.sendFile(path.join(__dirname), '../public/index.html');
});

【讨论】:

    【解决方案2】:

    尝试两件事:

    1. 删除script 标记内的document.getElementById("input").onchange,改为放入console.log('I am running the script tag')
    2. 输入console.log('I am rendering the App via react' inside of yourrendermethod, right abovereturn`。

    我想象script 标签在react 对DOM 做任何事情之前被“评估”,导致document.getElementById 不返回任何东西,因此你的null

    如果这是真的,您将在看到 I am rendering the App 之前看到您的 I am running the script tag

    【讨论】:

      猜你喜欢
      • 2020-10-31
      • 2015-01-30
      • 1970-01-01
      • 2015-05-27
      • 1970-01-01
      • 2016-02-24
      • 1970-01-01
      • 2017-08-19
      • 1970-01-01
      相关资源
      最近更新 更多