React-在渲染之外使用道具

时间:2019-02-18 01:54:43

标签: reactjs react-router-dom react-props

我试图将UserId发布到数据库,但Id作为prop传递。当我在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} />
          }
          />

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

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

3 个答案:

答案 0 :(得分:1)

这是一个范围问题:

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

答案 1 :(得分:0)

正如Binod所说,在初始状态下,将userId: null设置为null时,由于异步功能,在app.js中的API调用有时间返回之前,您的代码已执行。建议您在Asynchronous Javascript上查看此资源。

当您获得响应时,您的<Home />组件的道具将更新,并且会被传递,因此您需要做的是确保在传递userId之前不调用attendEvent()。您当前的代码无法显示当前如何调用它,但是我认为它在另一个componentDidMount中。尝试改用componentDidUpdate(),并检查是否props.userId !== null,然后进行API调用attendConcert

希望这会有所帮助,如果还有其他问题,请告诉我!

答案 2 :(得分:0)

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

OR

您还可以使用localStorage。

OR

尝试此操作,在路由到home组件之前进行null检查。

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