使用 "componentDidMount()" 重定向:问题(反应)

Redirect with "componentDidMount()" : problem (React)

我有一些有效的代码。它立即将用户从 /test 页面重新路由到 FinishedPaying 页面。是这样的:

class Test extends Component {
  renderRedirect = () => {
      return <Redirect to="/FinishedPaying" />;
  };
  componentDidMount() {
    this.renderRedirect();
  }
...

以下代码用于发送 Paypal 事务,然后将用户路由到 /FinishedPaying 页面。所有其他逻辑都按预期工作:

export default class Pay extends React.Component {
  state = {
    userInput: ""
  };
  renderRedirect = () => {
      return (
        <Redirect
          to="/FinishedPaying"
          userInput={this.state.userInput}
        />
      );
  };
  componentDidMount() {
    this.setState({ userInput: this.props.userInput });
    this.renderRedirect();
  }

  render() {
    const onSuccess = payment => {
      axios
        .post(
          "http://amazonaws.com:3000/ethhash",
          {
            userInput: this.props.userInput,
          }
        )

        .then(response => console.log(response.data, payment))

        .catch(function(error) {
          console.log(error);
        });
    };

    return (
      <div>
        <PaypalExpressBtn
          onSuccess={onSuccess}
        />
      </div>
    );
  }
}

不确定第二个代码块为何有效。我的理解是 this.renderRedirect() 应该在所有其他逻辑发生后触发。它似乎根本没有开火。感谢任何反馈:)

您不能在 componentDidMount 中 return 组件 <Redirect to="/FinishedPaying" />,您只能在 render() 中这样做。

当您准备重定向时,您可以设置一个设置为 true 的标志:

componentDidMount() {
  this.setState({
    userInput: this.props.userInput,
    readyToRedirect: true
  });
}

然后在你的render方法中:

render() {
  this.state.readyToRedirect
    ? <Redirect to="/FinishedPaying" />
    : other stuffs...

或者在我看来,更易读的方式:

render() {
  if (this.state.readyToRedirect) return <Redirect to="/FinishedPaying" />

  return (
    // rest of the code
  )

我也不会在render中定义onSuccess函数,每次状态变化都会触发渲染并一次又一次地重新定义函数。

如果不需要 this 中的任何内容,您甚至可以将其放在 class

之外
const onSuccess = payment => {
  ...
}

export default class Pay extends React.Component {
  ...
}

您可以将它放在您的 render 中,例如:

render() {
    if (this.state.redirect){
        return <Redirect
            to="/FinishedPaying"
            userInput={this.state.userInput}
            />;
    }
    const onSuccess = payment => {...}

一旦您将 state 中的 redirect 值更改为 true,您将被重定向。

export default class Pay extends React.Component {

 state = {
  redirect: false
 };

renderRedirect = () => {
  if(this.state.redirect){
   return (
     <Redirect
       to="/FinishedPaying"
       userInput={this.props.userInput}
     />
    );
  }
};

componentDidMount() {
  this.setState({ redirect: true });
}

render() {
const onSuccess = payment => {
  axios
    .post(
      "http://amazonaws.com:3000/ethhash",
      {
        userInput: this.props.userInput,
      }
    )

    .then(response => console.log(response.data, payment))

    .catch(function(error) {
      console.log(error);
    });
};

 return (
   <div>
    {this.renderRedirect()}
    <PaypalExpressBtn
      onSuccess={onSuccess}
    />
   </div>
  );
 }
}