我知道如何使用反应组件中的函数获取后端,但我需要一个下拉菜单,因此我在
react-select
页面中找到了一个示例,但该示例是在类中制作的。
我在互联网上找到的干净示例是这样的,对于导入
react-select
,需要运行命令npm install react-select
:
import React, { Component, Fragment, useEffect } from "react";
import Select from "react-select";
const options = [
{ value: "red", label: "red" },
{ value: "blue", label: "blue" },
{ value: "green", label: "green" }
];
export default class CrearPost extends Component {
state = {
selectedOption: null
};
handleChange = selectedOption => {
this.setState({ selectedOption });
// Option selected: { value: "red", label: "red" }
console.log(`Option selected:`, selectedOption);
};
render() {
return (
<div align="center">
<Fragment>
<Select
className="basic-single"
classNamePrefix="select"
defaultValue={options[0]}
isDisabled={false}
isLoading={false}
isClearable={true}
isRtl={false}
isSearchable={true}
name="color"
options={options}
onChange={this.handleChange}
/>
</Fragment>
<input
type="text"
placeholder="body"
/>
<button>
Submit post
</button>
</div>
);
}
}
所以我决定尝试进行 fetch,我尝试的是这样的:
import React, { Component, Fragment, useEffect, useState } from "react";
import Select from "react-select";
import { useHistory } from "react-router-dom";
const options = [
{ value: "red", label: "red" },
{ value: "blue", label: "blue" },
{ value: "green", label: "green" }
];
export default class CrearPost extends Component {
state = {
selectedOption: null
};
handleChange = selectedOption => {
/*I added all this*/
const [title, setTitle] = useState("");
const [body, setBody] = useState("");
const PostData = () => {
fetch('/createpost', { /*This route is in my nodejs server*/
method:'post',
headers:{
'Content-Type':'application/json',
Authorization: "Bearer " + localStorage.getItem("jwt")
},
body:JSON.stringify({
title,
body
})
}).then(res=>res.json())
.then(data=>{
console.log(data)
if(data.error){
alert(data.error)
}
else{
alert('Post created')
history.push('/')
}
}).catch(err=>{
console.log(err)
})
}
};
render() {
return (
<div align="center">
<Fragment>
<Select
className="basic-single"
classNamePrefix="select"
defaultValue={options[0]}
isDisabled={false}
isLoading={false}
isClearable={true}
isRtl={false}
isSearchable={true}
name="color"
options={options}
value={title}/*I added this*/
onChange={(e) => setTitle(e.target.value)}/*I added this*/
/>
</Fragment>
<input
type="text"
placeholder="body"
value={body}/*I added this*/
onChange={(e) => setBody(e.target.value)}/*I added this*/
/>
<button onClick={() => PostData()}/*I added this*/>
Submit post
</button>
</div>
);
}
}
希望有人能帮助我,谢谢。
类组件是有状态组件,有自己的状态。所以你不需要在类组件中使用useState。只需尝试将您的状态更改为:
this.state = {
title: "",
body: ""
};
不要忘记删除你的状态常量
根据错误消息的屏幕截图,它表示
useState
不能在基于类的组件中使用。 useState
是一个新的 React hook,为无类功能组件提供状态功能。
在基于类的组件中,您可以像我们之前那样使用 state = {...}
来代替。
所以代替这些行...
const [title, setTitle] = useState("");
const [body, setBody] = useState("");
将它们更改为...
state = {
selectedOption: null,
title: "",
body: ""
};
并将所有
setBody
和 setTitle
调用更改为状态更改调用。