【问题标题】:Passing an object as prop in React-Router Route在 React-Router Route 中将对象作为道具传递
【发布时间】:2020-08-21 18:06:00
【问题描述】:

我正在尝试使用路由中的渲染方法将对象道具传递给 Payments 组件。

我已经尝试将 props 传递给功能组件,但仍然没有成功。

App.js

class App extends Component {
  state = {
    user: {},
  };
  componentDidMount() {
    const url = "/api/current-user";
    fetch(url, {
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
      credentials: "same-origin",
      method: "GET",
    })
      .then((response) => {
        if (!response.ok) {
          return response.json().then((err) => {
            throw err;
          });
        }
        return response.json();
      })
      .then((results) => {
        const user = results.user;
        this.setState({
          user,
        });
      })
      .catch((error) => {
        console.log("Error", error);
      });
  }

  render() {
    console.log(this.state.user);
    
    return (
      <div className="container">
        <h1 className="is-size-3">Test</h1>
        {this.state.user && (
          <Route
            exact
            path="/payments"
            render={(props) => <Payments {...props} user={this.state.user} /> }
          />
        )}
      </div>
    );
  }
}

Payments.js

function Payments() {
  return (
    <>
      <CheckoutForm user={this.props.user} />
      <CurrentSubscription subscription={subscription} />
    </>
  );
}

我尝试了一些方法,但我仍然得到未定义的“道具”。

提前致谢

【问题讨论】:

  • 你想把 App.js 组件的 props 传递给 Payment.js 组件吗???还是只是 this.state.user??
  • App.js 的道具

标签: javascript reactjs


【解决方案1】:

这应该可以工作

function Payments(props) {
  return (
    <>
      <CheckoutForm user={props.user} />
      <CurrentSubscription subscription={subscription} />
    </>
  );
}

【讨论】:

    【解决方案2】:

    如果有 props,请始终将 props 放在函数或类组件中,如下所示:

    function Payments({user}) {
      return (
        <>
          <CheckoutForm user={user} />
          <CurrentSubscription subscription={subscription} />
        </>
      );
    }
    
    

    function Payments(props) {
      return (
        <>
          <CheckoutForm user={props.user} />
          <CurrentSubscription subscription={subscription} />
        </>
      );
    }
    
    

    顺便说一句,在功能组件中,没有this

    【讨论】:

      猜你喜欢
      • 2018-08-03
      • 2018-06-09
      • 2023-03-09
      • 2018-11-20
      • 2021-09-08
      • 2015-07-18
      • 1970-01-01
      • 1970-01-01
      • 2021-09-15
      相关资源
      最近更新 更多