到目前为止,我已经成功地通过Home.js
将信息插入到数据库(SQL,phpMyAdmin)中,但是问题是,每次用户输入信息并点击submit
时,它都会被重定向到我的demo.php
文件(未提供)而不是Next.js
。
换句话说,如何使用户信息成功进入数据库并转到下一页? (Next.js
)?
我在做什么错,我该如何解决?
这里是Home.js
:
import React, { Component } from 'react';
import Next from '../Home/Next';
class Home extends Component {
constructor(props) {
super(props);
this.state = {
show: false
};
this.getPHP = this.getPHP.bind(this);
this.goNext = this.goNext.bind(this);
}
getPHP() {
fetch(`http://localhost/demo_react/api/demo.php`, {
method: 'POST'
}).then(res => res.json())
.then(response => {
console.log('response');
console.log(response);
});
}
goNext() {
this.setState({show: true});
}
render() {
const next = this.state.show;
if(next) {
return <Next/>;
}
return (
<div>
<br/>
<form className="form-control" action="http://localhost/demo_react/api/demo.php" method={"POST"} encType="multipart/form-data">
<input type="text" name="username"/>
<input type="text" name="password"/>
<input type="submit" value="submit" onClick={this.getPHP & this.goNext} name={"submit"}/>
</form>
</div>
);
}
}
export default Home;
这里是Next.js
:
import React, { Component } from 'react';
class Next extends Component {
render() {
return(
<h1>made it</h1>
);
}
}
export default Next;
答案 0 :(得分:0)
您需要从表单中删除action属性,并在提交表单时调用getPHP()。另外,最好控制输入(输入更改时组件的状态更改)。有关更多信息,请参见此:Get form data in Reactjs
<form className="form-control" onSubmit={e => this.getPHP(e)}>
<input type="text" name="username" value={this.state.username} onChange={e => this.setState({ username: e.target.value })} />
<input type="text" name="password" value={this.state.password} onChange={e => this.setState({ password: e.target.value })} />
<input type="submit" value="submit" name="submit" />
</form>
您可以直接在getPHP()方法中访问表单值,因为现在可以控制输入:
constructor(props) {
super(props);
this.state = {
show: false,
username: '',
password: '',
};
}
getPHP(e) {
e.preventDefault();
const { username, password } = this.state;
const formData = new FormData();
formData.append('username', username);
formData.append('password', password );
fetch(`http://localhost/demo_react/api/demo.php`, {
method: 'POST',
headers: new Headers({ 'Content-Type': 'multipart/form-data' }),
body: formData,
})
.then(res => res.json())
.then(response => {
console.log('response');
console.log(response);
this.goNext();
});
}
最后,当获取成功时,您可以goNext()。