【发布时间】:2022-03-04 08:55:03
【问题描述】:
我想让用户在创建内容后移动主要组件,我不知道我需要使用什么方法。我想使用类似历史的东西,但它没有用。我正在使用
- “反应”:“^17.0.2”,
- "react-dom": "^17.0.2",
- "react-router-dom": "^6.2.1",
import React, { Component } from 'react';
class CreateContent extends Component {
constructor(props) {
super(props);
this.state = {
content: {
title: ''
}
}
}
handleInput = (e) => {
this.setState({
content : {
...this.state.content,
[e.target.name]: e.target.value
}
})
}
addContent = async (e) => {
e.preventDefault();
console.log(JSON.stringify(this.state.title))
try {
const response = await fetch('http://localhost:9000/api/v1/content', {
method: 'POST',
body: JSON.stringify(this.state.content),
mode:'cors',
headers: {
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
}
});
if(!response.ok) {
throw Error(response.statusText)
}
// ******* HERE I wanted to add something like *******
history.push('/main')
} catch (err) {
console.log('addContent failed -', err)
}
}
render() {
return (
<div>
<form onSubmit={this.addContent}>
<input
type="text"
name="title"
onChange={this.handleInput}
value={this.state.content.title}
/>
<input type="submit" value="submit" />
</form>
</div>
)
}
}
export default CreateContent
【问题讨论】:
-
您需要使用
React Router。如果我理解正确,您希望用户导航到某个自定义链接,如果是这样,请使用<Link to="/detail">Go To Details</Link>同样,您将有一些来自详细信息页面的链接返回到main页面。 -
@ParagDiwan 我想在函数内部使用它,这样我就可以让用户在他们成功 POST 请求后移动主页。我曾经使用 history.push 但我想它不再工作了..
标签: reactjs react-router react-router-dom