繁体   English   中英

尽管已经在componentDidMount()中设置了信息,但是在已经访问它之后,路由回它的组件仍无法以状态显示信息?

Routing back to component, after already visiting it, fails to display info in state even though its set in componentDidMount()?

提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供   中文繁体   英文版本   中英对照 版本,有任何建议请联系yoyou2525@163.com。

有一个问题,我的组件“要约”(应该为用户加载当前项目的要约)在离开路线并返回到路线后将无法加载要约(除非我刷新页面)。 我尝试了百万种解决此问题的方法,但无法使其正常工作。 我将状态填充在componentDidMount()中,该方法调用两个函数以将当前用户数据和当前用户提供的数据加载到状态中。 每次我路由到组件时,componentDidMount()都不应触发吗? 当我在路由返回后进入console.log状态时,offer数组为空。

import React, { Component } from 'react';
import App from "./App";
import firebase from "./firebase.js";
import {Redirect} from "react-router-dom";
import 'antd/dist/antd.css';
import { Layout, Form, Input, Icon, Card, Button, Col, Row, Menu, Avatar, Modal, DatePicker} from 'antd';
import './Offers.css';
import moment from 'moment';

const {RangePicker } = DatePicker;
const { Meta } = Card;
const { SubMenu } = Menu;
const { Header, Content, Footer, Sider } = Layout;
const Search = Input.Search;
const InputGroup = Input.Group;
const { TextArea } = Input;
const FormItem = Form.Item;


export default class Offers extends Component {
constructor(props) {
super(props);
this.state = {
    name: "",
    userid: "",
    password: "",
    redirect: false,
    redirectTarget: "",
    currentVendorItems: [],
    user: [],
    currentUserName: '',
    currentUserDescription: '',
    visible: false,
    description: '',
    currUserBuyerArray: [],
    currUserVendorArray: [],
    requestedPrice: 'None',
    rentalTime: [],
    visible: false,
    };
}

//Router
redirect = e => {
    this.setState({
        redirect: true, 
        redirectTarget: e
    });
}

//Handles canceling an offer, and therefore deleting it
handleDelete = (e) =>{
    firebase.database().ref('offers/' + e.id).remove();

    // **** Might need to just remove it from the current state array to save time ****
    this.getOfferInfo();
    this.handleRented(e.itemID, false);
}

//Handles vendor rejecting, so buyer can cancel or make a counter offer
handleReject = (e) =>{
    firebase.database().ref('offers/' + e.id).update({
        status: "Rejected"
    });
    this.getOfferInfo();
}

//Handles acceptance of an offer, buyer now will have option to pay
handleAccept = (e) =>{
    firebase.database().ref('offers/' + e.id).update({
        status: "Accepted"
    });
    this.getOfferInfo();
    this.handleRented(e.itemID, true);
}

handleRented = (e, boolean) =>{
    firebase.database().ref('items/' + e).update({
        itemRented: boolean
    });
}

//Modal Functions
showModal = () => {
    this.setState({
      visible: true,
    });
}

handleOk = (e) => {
    this.setState({
      visible: false,
    });
}

handleCancel = (e) => {
    this.setState({
      visible: false,
    });
}

//Disables days before the current day
disabledDate = (current) => {
  // Can not select days before today and today
  return current && current < moment().endOf('day');
}

//Handles time string entered
handleTime = (value, dateString) => {
  this.setState({
    rentalTime: dateString
  })
}

//Handles additonal info inputted
handlePrice = (e) => {
    e.preventDefault();
    this.setState({
        requestedPrice: e.target.value
    });
}

//Handles submission of a counter offer on a rejected item
handleSubmit = (date, reqPrice, offerID) => {
    firebase.database().ref('offers/' + offerID).update({
        status: "Pending",
        date: date,
        requestedPrice: reqPrice
    });
    this.getOfferInfo();
    this.handleCancel();
}

getUserInfo = () => {
    firebase.auth().onAuthStateChanged( authUser => {
      if (authUser) {
        // User is signed in.
        //Auth database reference
        var user = firebase.auth().currentUser
        this.setState({
            user: firebase.auth().currentUser
        });

      } else {
        // No user is signed in.
        console.log('we messed up somewhere!')
      }
    });
}

getOfferInfo = () =>{        
    const currUserOffersRef = firebase.database().ref('offers/');
    currUserOffersRef.on('value', (snapshot) => {
        let offersSnapshot = snapshot.val();

        let buyerOffersArray = []
        let vendorOffersArray = []

        for (let offer in offersSnapshot) {
            //If the user id == the user id on the offer, they made it
           if (this.state.user.uid === offersSnapshot[offer].userUID){
            buyerOffersArray.push({
                id: offer,
                name: offersSnapshot[offer].name,
                date: offersSnapshot[offer].date,
                info: offersSnapshot[offer].info,
                itemID: offersSnapshot[offer].itemID,
                userUID: offersSnapshot[offer].userUID,
                vendorUID: offersSnapshot[offer].vendorUID,
                price: offersSnapshot[offer].price,
                requestedPrice: offersSnapshot[offer].requestedPrice,
                status: offersSnapshot[offer].status,
            });
           }
           //if the user id == the vendor id on the offer, they created the listing
           if (this.state.user.uid === offersSnapshot[offer].vendorUID){
            vendorOffersArray.push({
                id: offer,
                name: offersSnapshot[offer].name,
                date: offersSnapshot[offer].date,
                info: offersSnapshot[offer].info,
                itemID: offersSnapshot[offer].itemID,
                userUID: offersSnapshot[offer].userUID,
                vendorUID: offersSnapshot[offer].vendorUID,
                price: offersSnapshot[offer].price,
                requestedPrice: offersSnapshot[offer].requestedPrice,
                status: offersSnapshot[offer].status,
            });
           }
        }
        this.setState({
            currUserBuyerArray: buyerOffersArray,
            currUserVendorArray: vendorOffersArray
        });
        })
}

// On component mount, get info from DB and auth as well as the offer info
componentDidMount() {
    this.getUserInfo();
    this.getOfferInfo();
}

render() {
    //Router
    if(this.state.redirect === true){
        return <Redirect to= {this.state.redirectTarget} />;
    }
    console.log(this.state)
    return (
    <Layout>
    <Layout className="layout-header">
        <Header>
            <div className="logo" />
            <Menu
            theme="dark"
            mode="horizontal"
            defaultSelectedKeys={['2']}
            style={{ lineHeight: '64px' }}
            >
            <Menu.Item key="1" onClick={e => this.redirect("/Marketplace")}>Marketplace</Menu.Item>
            <Menu.Item key="2" onClick={e => this.redirect("/Profile")}>Profile</Menu.Item>
            <Menu.Item key="3" onClick={e => this.redirect("/VendorPage")}>Create Listing</Menu.Item>
            </Menu>
        </Header>

    <Layout className="layout-main">
        <Sider width={300} style={{ background: '#fff' }}>
            <Menu
              mode="inline"
              defaultSelectedKeys={['3']}
              style={{ height: '100%', borderRight: 0 }}
            >
            <Menu.Item key="1" onClick={e => this.redirect("/Profile")}>Profile</Menu.Item>
            <Menu.Item key="2" onClick={e => this.redirect("/MyItems")}>My Items</Menu.Item>
            <Menu.Item key="3">Offers</Menu.Item>
            </Menu>
        </Sider>
        <Layout className="layout-profile">
            <div className= "offers-other-items" style={{margin: 40}}>
            <Row>
                <Col span = {22}>
                <Card title="My Offers">
                { //Checks if the array is empty, and lets the user know if there are no offers
                    (this.state.currUserBuyerArray.length == 0)
                    ? <div>You have no current offers on items</div> 
                    : 
                    <div> 
                    {this.state.currUserBuyerArray.map(offer => {
                    return (
                    <div>
                    <Row>
                    <Col span={20} offset={2}>
                        <div className="card" style={{background: "#c4c4c4", width: "100%", margin: "0 auto"}}>
                        <Card className="card-content" title={offer.name + "  -  " + offer.status}>
                        Intial Price: ${offer.price} <br/>
                        Requested Price: ${offer.requestedPrice} <br/>
                        Requested Dates: {offer.date[0]}  to  {offer.date[1]} <br/>
                        <div>
                            {
                                (offer.status === "Pending")  
                                ? <div className="offersButton">
                                <Button type="primary" icon="delete" onClick={e => this.handleDelete(offer)}>Cancel Offer</Button>
                                </div>
                                : <div></div>
                            }
                            {
                                (offer.status === "Accepted")  
                                ? <div className="offersButton">
                                <Button type="primary" icon="delete" onClick={e => this.handleDelete(offer)}>Cancel Offer</Button>
                                <Button type="primary" icon="check" onClick={e => this.handlePayment(offer.id)}>Payment</Button>
                                </div>
                                : <div></div>
                            }
                            {
                                (offer.status === "Rejected")  
                                ?
                                <div className="offersButton">
                                <Button type="primary" icon="delete" onClick={e => this.handleDelete(offer)}>Cancel Offer</Button> 
                                <Button type="primary" icon="check" onClick={e => this.showModal()}>Make another Offer</Button>
                                <Modal
                                  visible={this.state.visible}
                                  onOk={this.handleOk}
                                  onCancel={this.handleCancel}
                                  footer={[
                                    <Button key="back" onClick={this.handleCancel}>Cancel</Button>,
                                    <Button type="primary" onClick={e => this.handleSubmit(this.state.rentalTime, this.state.requestedPrice, offer.id)}>
                                    Request
                                    </Button>
                                  ]}
                                >
                                <RangePicker
                                    disabledDate={this.disabledDate}
                                    format="MM-DD-YYYY"
                                    placeholder={['Start Time', 'End Time']}
                                    onChange={this.handleTime}
                                />
                                <p style = {{color: "red"}}> {this.state.errorMessage}</p>
                                <p>Request a different price (Optional)</p>
                                <Input
                                    placeholder="Requested Price"
                                    onChange={this.handlePrice}
                                />
                                </Modal>
                                </div>
                                : <div></div>
                            }        
                        </div>
                        </Card>
                        </div>
                    </Col>
                    </Row>
                    <br />
                    </div>
                    )
                    })
                    }
                    </div> 
                    }
                </Card>
                </Col>
            </Row>
            </div>
            <div className="offers-my-items" style={{margin: 40}}>
            <Row>
                <Col span = {22}>
                <Card title="Offers on my Items">

                { //Check if message failed
                    (this.state.currUserVendorArray.length == 0)
                    ? <div>There are no offers on your items</div> 
                    : 
                    <div>
                    {this.state.currUserVendorArray.map(offer => {
                    return (
                    <div>
                    <Row>
                    <Col span={20} offset={2}>
                        <div className="card" style={{background: "#c4c4c4", width: "100%", margin: "0 auto"}}>
                        <Card className="card-content" title={offer.name + "  -  " + offer.status}>
                        Intial Price: ${offer.price} <br/>
                        Requested Price: ${offer.requestedPrice} <br/>
                        Requested Dates: {offer.date[0]}  to  {offer.date[1]} <br/>
                        <div>
                            {
                            (offer.status === "Pending")  
                            ? <div className="offersButton">
                            <Button type="primary" icon="delete" onClick= {e => this.handleReject(offer.id)}>Reject</Button>
                            <Button type="primary" icon="check" onClick= {e => this.handleAccept(offer)}>Accept</Button>
                            </div>
                            : <div></div>
                            }
                            {
                            (offer.status === "Rejected")  
                            ? <div className="offersButton">
                            <p>Awaiting counter offer from buyer, or you can delete the offer </p>
                            <Button type="primary" icon="delete" onClick= {e => this.handleDelete(offer)}>Cancel Offer</Button>
                            </div>
                            : <div></div>
                            }
                        </div>
                        </Card>
                        </div>
                    </Col>
                    </Row>
                    <br/>
                    </div>
                    )
                    })
                    }    
                </div> 
                }
                </Card>
                </Col>
            </Row>
            </div>
        </Layout>
        </Layout>
        </Layout>
    </Layout>
    );
    }
}
问题暂未有回复.您可以查看右边的相关问题.
2 已经访问过的组件如何刷新?

在进行项目和更改路线时,在已经访问过项目之后返回一个不会显示新的更改/添加。 例如,如果我转到“要约”路线,它将在当前要出租的物品上显示我的要约。 如果我随后离开该路线并在项目上放置另一个要约,则路由到“要约”将不会显示任何更改,除非我刷新页面。 我在componentdidmount() ...

2018-11-14 00:54:49 1 43   reactjs
3 即使在状态更改后,如何使用 componentDidMount?

我在学习 React 时遇到了这段代码: 问题是即使在状态改变后,componentDidMount 是如何被调用的,也就是说, 在上面的代码 setInterval 被调用,它又调用改变状态的滴答函数。 但是状态改变后,组件重新渲染后,是不是又调用了componentDidMount? ...

2020-03-25 19:33:44 3 33   reactjs
5 即使视频(及其容器)设置为“显示:无”,也能播放音频

我有一个 Brightcove 视频,该视频设置为带声音自动播放,但仅当在移动设备上查看该页面时才会播放。 我设置了一个媒体查询来让视频和它的容器在桌面上设置为“显示:无”。 但是,音频仍然在桌面上播放。 我怎样才能关闭它? 这是否可以仅使用 CSS 来实现,最好不要弄乱播放器本身或添加 Java ...

7 在componentDidMount中设置后,反应状态未定义

这是演示文稿文件: 这是容器文件: React不会重新呈现,并且控制台日志错误是“无法读取未定义的属性'列表'”在将表单移入演示文件之前,它工作正常。 这是对我的培训,我很想了解发生了什么 ...

8 即使我已经通过事件对其进行了更改,alert($(“#myHTMLElement”))为什么仍显示其原始属性?

我有这个功能,应该创建一个棋盘格。 这是将白色正方形的css背景颜色“突变”为绿色的函数。 这是单击正方形时调用的函数。 如果正方形是绿色,则应说“恭喜”,否则将仅声明它是白色正方形。 线 说“#a6”的background-color属性现在具有值“ rgb( ...

9 导致React组件的属性和状态没有变化的原因是什么?

我有一个组件,它的道具由父组件设置。 父组件定期更改,但孩子的道具不更改。 但是由于某种原因,孩子继续渲染,但我不知道为什么。 为了验证道具和状态没有改变,我添加了以下功能: 这将在控制台中打印以下内容: 因此,从一个调用到下一个调用,状态和prop严格相等,但是该组件 ...

2017-11-29 19:35:04 1 106   reactjs
暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2021 STACKOOM.COM