React - 在 Render 之外使用 Props

React - Using Props outside of Render

我正在尝试将 UserId post 传递给数据库,但该 Id 作为道具传递。当我在 render 方法中输入 this.props.userId 时,它会显示所需的信息,但是当我尝试将其合并到 render 函数上方的函数中时,我得到 null。我花了几个小时审查其他 postings 并尝试了我能做的一切都无济于事。

App.js代码

import axios from 'axios'
import {
  BrowserRouter as Router,
  Route,
  Redirect,
} from 'react-router-dom'
import Home from "./pages/Home";
import MyEvents from "./pages/MyEvents"
import Signup from "./pages/Signup";
import Login from "./pages/Login";
import Navbar from "./components/Navigation/Navigation";
import "./App.css"


class App extends Component {
  constructor() {
    super()
    this.state = {
      loggedIn: false,
      username: null,
      userId: null,
    }

    this.getUser = this.getUser.bind(this)
    this.componentDidMount = this.componentDidMount.bind(this)
    this.updateUser = this.updateUser.bind(this)
  }

  componentDidMount() {
    this.getUser()
  }

  updateUser (userObject) {
    this.setState(userObject)
  }

  getUser() {
    axios.get('/api/users/').then(response => {
      console.log('Get user response: ')
      console.log(response.data)
      if (response.data.user) {
        console.log('Get User: There is a user saved in the server session: ')

        this.setState({
          loggedIn: true,
          username: response.data.user.username,
          userId: response.data.user._id
        })
      } else {
        console.log('Get user: no user');
        this.setState({
          loggedIn: false,
          username: null,
          userId: null
        })
      }
    })
  }

  render() {
    return (
      <div className="App">

        <Navbar updateUser={this.updateUser} loggedIn={this.state.loggedIn} />
        {/* greet user if logged in: */}
        {this.state.loggedIn &&
          <p>You are logged in, {this.state.username}, userId: {this.state.userId}!!!!</p>
        }
        {/* Routes to different components */}
        <Route
          exact path="/home"
          render = {() => 
            <Home userId = {this.state.userId} />
          }
          />

Home.js代码

import React, { Component } from "react";
import API from "../utils/API";
class Events extends Component {
  state = {
    events: [],
    search: "",
    selector: "",
    input:""
    };


  attendEvent = show => {
    API.attendConcert({
      userId: this.props.userId,
      concertId: show.id,
      artist: show.performance[0].artist.displayName,
      venue: show.venue.displayName,
      date: show.start.date,
      time: show.start.time,
      city: show.venue.metroArea.displayName,
      latitude: show.venue.lat,
      longitude: show.venue.lng,
    })
    .then(res => window.location.href = "/concerts/" + res.data._id)
    .catch(err => console.log(err))
  }

  handleRadioChange = event => {
    this.setState({
      selector: event.target.value
    });
  }


  render() {
    return (<>
      <Container>
        <Row>
          <Col size="md-12">
<p>Hi {this.props.userId}</p>

API.JS代码

import axios from "axios";

export default {
    attendConcert: function(eventData) {
        return axios.post("/api/concerts", eventData);
    },
    getConcert: function(id) {
        return axios.get("/api/concerts/" + id);
    }
}

注意:删除了一些代码行以减少所呈现的代码量,但如果有人希望查看所有内容,请告诉我。

正如 Binod 评论的那样,你得到 userId: null 因为你最初在你的状态下将它设置为 null,并且你的代码在 app.js 中的 API 调用有时间之前执行由于异步功能回来。我建议在 Asynchronous Javascript.

上查看此资源

你的 <Home /> 组件的 props 会在你得到响应时更新,并会被传递下来,所以你需要做的是确保 attendEvent() 在 userId 被传递之前没有被调用.您当前的代码目前没有显示这是如何调用的,但我假设它在另一个 componentDidMount 中。尝试改用 componentDidUpdate() 并检查是否 props.userId !== null,然后进行 API 调用 attendConcert

希望这对您有所帮助,如果您还有任何问题,请告诉我!

您可以尝试从 componentDidMount() 调用函数。因为一切都是异步的。您的状态未在父组件中设置,而是在子组件中用作道具。我也遇到过同样的问题。道具在 child 的 render() 中呈现,而不是在其他任何地方。

您也可以使用 localStorage。

试试这个,在路由到主组件之前进行空检查。

   {this.state.userId ?
   <Route
      exact path="/home"
      render = {() => 
        <Home userId = {this.state.userId} /> : null}

这是一个范围问题:

API.attendConcert({
      userId: this.props.userId,
      concertId: show.id,
      artist: show.performance[0].artist.displayName,
      venue: show.venue.displayName,
      date: show.start.date,
      time: show.start.time,
      city: show.venue.metroArea.displayName,
      latitude: show.venue.lat,
      longitude: show.venue.lng,
    })

this 在该上下文中指的是您正在构建的对象文字,而不是组件。

声明一个变量来保存 userId 的值,然后在对象字面量中使用该值,如下所示:

const userId = this.props.userId
API.attendConcert({
     userId: userId,
      concertId: show.id,
      artist: show.performance[0].artist.displayName,
      venue: show.venue.displayName,
      date: show.start.date,
      time: show.start.time,
      city: show.venue.metroArea.displayName,
      latitude: show.venue.lat,
      longitude: show.venue.lng,
    })