Redirect to Another component passing props id parameter on url

萝らか妹 提交于 2021-01-28 19:02:48

问题


When I'm inserting a todo in Todo Form, I want get todo's id product when I click in create and redirect to url from component Show Product.

This is my code in New Todo.jsx:

import React, { Component } from 'react';

 import { connect } from 'react-redux';
 import { Redirect } from 'react-router';
 import { SubmissionError } from 'redux-form';
 import { newTodo, saveTodo } from '../../actions/todoActions';
    import TodoForm from './TodoForm';

class NewTodo extends Component {
   state = {
     redirect: false
   };

  componentDidMount() {

    this.props.newTodo();

  }

  submit = todo => {
    return this.props
      .saveTodo(todo)
       .then(response => this.setState({ redirect: true }))
       .catch(err => {
         throw new SubmissionError(this.props.errors);
          });
      };

  render() {
     return (
       <div>
        <h2>New Todo</h2>

        {this.state.redirect ? (
           <Redirect to={{
            pathname: `/todos/${this.props.todo.state.id}/show`,
            state: {  id: this.props.match.params}
          }} />
        ) : (
      <TodoForm todo={this.props.todo} onSubmit={this.submit} />
        )}
      </div>
     );
   }
}

 function mapStateToProps(state) {
  return {
    todo: state.todosDs.todo,
     errors: state.todosDs.errors
  };
}

export default connect(
  mapStateToProps,
  { newTodo, saveTodo }
)(NewTodo);

I expect something like this: '/todos/s31uju1uj1jujw11ij/show' but this is real output: '/todos/undefined/show'

What is wrong?


回答1:


Make sure that you are passing here your id

<Redirect to={{
            pathname: `/todos/${this.props.todo.state.id}/show`,
            state: {  id: this.props.todo.state.id }   

I think it might be

     { this.props.todo.id } // change it as per your id 
     state: {  id: this.props.todo.id }

Try to log

 render() {
     console.log('todo', this.props.todo); // add log and check you are getting your todo 
     return (


来源:https://stackoverflow.com/questions/59930022/redirect-to-another-component-passing-props-id-parameter-on-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!