【问题标题】:Redirect to another component with url passing id like parameter重定向到另一个带有 url 传递 id 参数的组件
【发布时间】:2020-02-23 22:07:46
【问题描述】:
【问题讨论】:
标签:
javascript
reactjs
react-redux
redux-form
【解决方案1】:
我相信这样的事情会奏效。
很确定您尝试访问的 todoId 在最终 URL 中未定义,因为您在 then 语句中设置它并且它不是状态的一部分。因此,当状态更新触发重新渲染时,它会将其重置为 null。
class NewTodo extends Component {
state = {
redirect: ''
};
componentDidMount() {
this.props.newTodo();
}
//In the following lines have to do much lines. I need to get todo if from api rest.
submit = todo => {
return this.props
.saveTodo(todo)
.then(response => {
console.info(response);
this.setState({ redirect: response._id});
})
.catch(err => {
throw new SubmissionError(this.props.errors);
});
};
render() {
return (
<div>
<h2>New Todo</h2>
{this.state.redirect ? (
<Redirect to={"/todos/" + this.state.redirect + "/show"} />
) : (
<TodoForm todo={this.props.todo} onSubmit={this.submit} />
)}
</div>
);
}
}
由于空字符串是虚假的,因此三元条件只应在 state 的重定向属性已设置的情况下评估为真。