【问题标题】:Redirect to another component with url passing id like parameter重定向到另一个带有 url 传递 id 参数的组件
【发布时间】:2020-02-23 22:07:46
【问题描述】:

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

因此,通过 url 传递的类似参数的 todo id 是未定义的。我看到 '/todos/undefined/show' 而不是 '/todos/134ls5/show' 我在 Todo 表单中填写的数据,其中 134ls5 是创建的 todo 的 id。

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

【问题讨论】:

标签: 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 的重定向属性已设置的情况下评估为真。

【讨论】:

    猜你喜欢
    • 2015-10-14
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-24
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多