首页 > 解决方案 > 从 express 操作数据的问题

问题描述

我是 express 的新手并做出反应尝试制作我的第一个应用程序,但我在处理来自 express 的数据时遇到问题。表达

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const port = process.env.PORT || 5000;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/favcolors', (req, res) => {
    const colors = [
        'red',
        'green',
        'yellow'
    ];
    res.json(colors);
});

app.listen(port, () => console.log(`Listening on port ${port}`));

反应

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { 
      colors: []
    }
  }
  callApi = async () => {
    const response = await fetch('/favcolors');
    const body = await response.json();
    if (response.status !== 200) throw Error(body.message);

    return body;
};
  componentDidMount() {
  this.callApi()
  .then(colors => this.setState({colors}, () => console.log('Fetch data ', colors)));
  console.log(this.state.data)
}
wantYellow = () => {
  this.setState({});
};
  render() {
    return (
      <div>
        <h1>
          Fav colors: {this.state.colors[0]}
        </h1>
        <button type="button" onClick={this.wantYellow}>
          Change
        </button>
      </div>
    );
  }
}
export default App;

我想使用按钮将“Fav Color”从红色 - this.state.colors 更改为黄色,但我不知道该怎么做。你能给我一些例子吗?

标签: reactjsexpress

解决方案


这样做的一种方法是保持index颜色state如下:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { 
      colors: [],
      index: 0
    }
    this.wantYellow = this.wantYellow.bind(this);
  }
  callApi = async () => {
    const response = await fetch('/favcolors');
    const body = await response.json();
    if (response.status !== 200) throw Error(body.message);

    return body;
};
  componentDidMount() {
  this.callApi()
  .then(colors => this.setState({colors}, () => console.log('Fetch data ', colors)));
  console.log(this.state.data)
}
wantYellow = () => {
  this.setState({ index: 2 });
};
  render() {
    return (
      <div>
        <h1>
          Fav colors: {this.state.colors[this.state.index]}
        </h1>
        <button type="button" onClick={this.wantYellow}>
          Change
        </button>
      </div>
    );
  }
}
export default App;

希望这会帮助你。


推荐阅读