reactjs - 从 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 更改为黄色,但我不知道该怎么做。你能给我一些例子吗?
解决方案
这样做的一种方法是保持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;
希望这会帮助你。
推荐阅读
- sql - 查找 SQL 中连续行之间的年份差异?
- vee-validate - vee-validate 3 个可选地址字段,但一个是必需的
- php - 小改动的 Git 工作流程
- react-native - 在本机反应中通过图像中的路径时出错
- kotlin - 有没有办法使用数据生成 kotlin dsl
- firebase - 为什么我无法在 Firestore Flutter 中使用这些功能更新 imageurl?
- python-3.x - xlwings 找不到 XL 应用程序
- android - 单击 MenuIcons 时 Android Studio 应用程序崩溃
- vertex - 如何更改 PORTA 输出中的不等式表示?
- r - `purrr:map()` 打印列表中的项目及其名称