使用 url 传递 id 之类的参数重定向到另一个组件

Redirect to another component with url passing id like parameter

在 TodoForm.jsx 中,我正在创建待办事项,当我单击创建按钮时,未定义 Todo.jsx 中的响应。

因此,url 传递的类似参数的待办事项 ID 未定义。我看到“/todos/undefined/show”而不是“/todos/134ls5/show”,其中包含我在待办事项表单中填写的数据,其中 134ls5 是创建待办事项的 ID。

更多信息,请参见In BillForm create or edit a todo and redirect to ShowTodo not ListTodo

我相信这样的事情会奏效。

很确定您尝试访问的 todoId 最终未定义 URL 因为您是在 then 语句中设置它并且它不是状态的一部分。因此,当状态更新触发重新渲染时,它会将其重置为空。

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>
        );
    }
}

由于空字符串是假的,三元条件应该只评估为真,状态的重定向 属性 已设置。