[英]Next.js Shallow Routing from Textinput Form Submit
我在Next.js和React中相对较新,
我想在此处基于Next.js示例的提交表单中基于textinput状态设置浅层url。
尝试修改它以使用表单:
render() {
const {initialText, router} = this.props
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
但是,我还是不能this.state.value转移到{ router }
/ this.props
上handleSubmit
所以它会在浏览器中路线显示...
如果有人可以给我一个提示,请继续进行..谢谢..
其余代码大致模仿该示例:
static getInitialProps({ res }) {
if (res) {
return { initialText: 'none' }
}
text = this.state.value;
return {
initialText: text
}
}
constructor (props) {
super(props);
this.state = {value: 'none'};
}
handleChange = (event) => {
this.setState({ value: event.target.value });
}
handleSubmit = (event) => {
const { router } = this.props
const currentText = router.query.text
? router.query.text
: 'none'
const href = `/?text=${currentText}`
Router.push(href, href, { shallow: true })
}
为了能够使用getInitialProps()
,您需要使用此页面,因为它在子组件中不起作用。 因此,如果在子组件中使用getInitialProps()
,则initialText
将始终是未定义的。 在子Component中,您需要使用componentDidMount()
并将state设置为initialText
。
因此,考虑到您已经在页面,文件夹中定义了此组件,它应该可以工作。 但是,如果您将以下内容定义为子组件,则它将不起作用。
static getInitialProps({ res }) {
if (res) {
return { initialText: 'none' }
}
text = this.state.value;
return {
initialText: text
}
}
constructor (props) {
super(props);
this.state = {value: 'none'};
}
handleChange = (event) => {
this.setState({ value: event.target.value });
}
handleSubmit = (event) => {
const { router } = this.props
const currentText = router.query.text
? router.query.text
: 'none'
const href = `/?text=${currentText}`
Router.push(href, href, { shallow: true })
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.