问题
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