【发布时间】:2020-10-12 14:42:08
【问题描述】:
非常感谢您的帮助。我在 Web 开发和使用 ReactJS 方面非常陌生。 我正在尝试创建一个登录页面,使用电子邮件和密码作为凭据。问题是,如果我将我的 fetch 函数放在 ComponentDidMount 中,我会收到 404 错误,但如果我将它从生命周期方法中取出,它会连接到服务器并且我会在终端中收到用户的详细信息 - 我还不知道如何将它们放入控制台或我的反应应用程序中。如果您能提出一种方法,将不胜感激。我正在尝试获取当前登录的用户详细信息。
这是我的构造方法:
export default class Login extends React.Component {
constructor(props){
super(props);
this.state = {
user:[],
email:'',
password:''
}
对于电子邮件和密码输入,我在表单中附加了一个 handleChange 函数: 这是表单输入的函数:
handleChange = (e) =>{
this.setState({
[e.target.name]: [e.target.value]});
}
这是形式:
<input
type= "email"
name="email"
placeholder="Email address"
value={this.state.email}
onChange={event => this.handleChange(event)}
required
/>
<input
type="password"
name="password"
placeholder="Password"
value={this.state.password}
onChange={event => this.handleChange(event)}
required
/>
这是我在生命周期方法中的 fetch 函数:
async componentDidMount(){
const url = 'http://localhost:3000/login';
const options = { method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': '*/*'
},
body: JSON.stringify({email:this.state.email, password:this.state.password})
};
const response = await fetch(url,options);
let data = response.json();
this.setState({user: data.results})
}
在这个阶段,我在控制台中收到 404 错误:( POST http://localhost:3000/login 404 (Not Found),在终端中我收到此错误:
data:: {}
user:: []
user.length:: 0
TypeError: Cannot read property 'password' of undefined
at authenticateUser (/Users/noir/Documents/Dana/work/SocialCats/backend/controllers/login.js:16:16)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
如果我切换到 Postman,它可以在同一个 url 上正常工作。
如果我将我的 fetch 函数从生命周期方法中取出,那么它可以对用户进行身份验证,并在我的终端中获取用户详细信息。 知道为什么会这样吗? 每一个帮助都非常有价值,因为我被困在这里。 谢谢:)
【问题讨论】:
-
你得到的错误是:
TypeError: Cannot read property 'password' of undefined。我猜在componentDidMount中,this.state尚未定义。 -
如果你想使用生命周期方法,试试
componentWillMount
标签: reactjs post fetch react-lifecycle