Reactjs 反应-使用渲染外的道具

Reactjs 反应-使用渲染外的道具,reactjs,react-router-dom,react-props,Reactjs,React Router Dom,React Props,我试图将用户Id发布到数据库,但该Id作为道具传递。当我在render方法中输入this.props.userId时,它会显示所需的信息,但是当我尝试将其合并到render函数上方的函数中时,我会得到null。我花了好几个小时来查看其他帖子,并尽我所能尝试各种感觉,但都无济于事 App.js代码 import axios from 'axios' import { BrowserRouter as Router, Route, Redirect, } from 'react-rout

我试图将用户Id发布到数据库,但该Id作为道具传递。当我在render方法中输入this.props.userId时,它会显示所需的信息,但是当我尝试将其合并到render函数上方的函数中时,我会得到null。我花了好几个小时来查看其他帖子,并尽我所能尝试各种感觉,但都无济于事

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} />
          }
          />
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所评论的,当您最初在您的状态中将其设置为null时,您将获得
userId:null
,并且由于异步功能,您的代码在app.js中的API调用返回之前执行。我建议您在上查看此资源

您的
组件的道具将在收到响应时更新,并将被传递,因此您需要做的是确保在传递用户ID之前未调用
attendEvent()
。您当前的代码没有显示当前如何调用它,但我假设它位于另一个
组件didmount
中。尝试改用并检查是否
props.userId!==null
,然后进行API调用
attendConcert


希望这有点帮助,如果你还有任何问题,请告诉我

您可以尝试从componentDidMount()调用函数。因为一切都是异步的。您的状态未在父组件中设置,并且正在子组件中用作道具。我也面临同样的问题。道具在子级的render()中渲染,但不在其他任何位置渲染

您还可以使用本地存储

尝试此方法,在路由到主组件之前进行空检查

   {this.state.userId ?
   <Route
      exact path="/home"
      render = {() => 
        <Home userId = {this.state.userId} /> : null}
{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,
    })
在该上下文中指的是您正在构建的对象文本,而不是组件

声明一个变量以保存用户ID的值,然后在对象文本中使用该值,如下所示:

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,
    })

是的,用户ID一开始是空的,因为您首先定义了空的用户ID状态,当api抛出响应时,它将被设置为setState(更新)。但是在api抛出响应之前,已经呈现了routh路径。因此,可以在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,
    })