【问题标题】:Adding the value from my third party API to my the state of the account balance将我的第三方 API 的值添加到我的帐户余额状态
【发布时间】:2020-07-17 20:49:45
【问题描述】:

我目前正在开发一个项目,该项目使用第三方 API 和来自https://finnhub.io/login 的证券交易所信息我目前已经获得了报价(价格)信息以呈现状态,但我想访问当前价格并拥有一个购买功能影响帐户余额的状态,并在每次单击购买按钮时将 stockShares 加 1。我的数据库资源中有两个模型,一个用户我想将股票信息添加到

import React, { Component } from 'react'
import axios from 'axios'
import * as ReactBootStrap from "react-bootstrap"






export default class Home extends Component {
    state = {


        symbol: {
            enteredSymbol: ' ',

        },

        user: {
            stockShares: 0,
            accountBalance: 1000000,
        }

}

// getting user information
getUserInfo = () =>{
    axios.get('/api/user').then((response)=>{
        this.setState({
            user : response.data.accountBalance
        })
    })
}




//functions for stock api calls
    changeInput = (event) =>{
        const newSymbol = {...this.state.symbol}
        newSymbol[event.target.name] = event.target.value
        this.setState({
            symbol: newSymbol
        })
    }

    onSubmitSymbol = (event) =>{
        event.preventDefault();
        axios.get(`https://finnhub.io/api/v1/quote?symbol=${this.state.symbol.enteredSymbol}&token=bq3klmvrh5rb0pdpe5ng`).then((response)=>{
            const current = response.data.c;
            const high = response.data.h;
            const low = response.data.l;
            const open = response.data.o;
            const close = response.data.pc;
            const timeStamp = response.data.t;


            this.setState({
                currentPrice: current,
                highPrice: high,
                lowPrice: low,
                openPrice: open,
                closePrice: close,
                time: timeStamp,
            })

            return axios.get('https://finnhub.io/api/v1/stock/symbol?exchange=US&token=bq3klmvrh5rb0pdpe5ng')
        }).then((name)=>{
            const newName = name.data;
            for(let i = 0; i < newName.length; i++){
                if ( newName[i].displaySymbol === this.state.symbol.enteredSymbol){
                    this.setState({

                        stockName: newName[i].description

                    })

                }



            }
        })
    }

    //end of api calls for getting stock information

    //start of buying stocks for the user account

    buyStock = (event) =>{
        event.preventDefault()
        axios.get(`https://finnhub.io/api/v1/quote?symbol=${this.state.symbol.enteredSymbol}&token=bq3klmvrh5rb0pdpe5ng`).then((response)=>{

            let current = parseInt(response.data.c);

            let balance = parseInt(this.state.accountBalance);

            // const newStockShares = {...this.state.user.stockShares}
            if ( balance > current) {
                balance.push(current);
                this.setState({
                    newBalacne: current += balance,
                    stockShares: + 1,
                })

            } else {
                alert('you do not have enough moeny for a share in this stock');
            }


        })

    }

    componentDidMount(){
        this.getUserInfo()
    }












    render() {
        return (
            <div>



                <ReactBootStrap.Navbar bg="dark" variant="dark">
    <ReactBootStrap.Navbar.Brand href="#home">The Stock App</ReactBootStrap.Navbar.Brand>
    <ReactBootStrap.Nav className="mr-auto">
      <ReactBootStrap.Nav.Link href="#home">Home</ReactBootStrap.Nav.Link>
      <ReactBootStrap.Nav.Link href="/resources">Resources</ReactBootStrap.Nav.Link>
      <ReactBootStrap.Nav.Link href="http://eoddata.com/symbols.aspx" target="_blank">Symbols</ReactBootStrap.Nav.Link>
      <ReactBootStrap.Nav.Link href="/account">My Account</ReactBootStrap.Nav.Link>
    </ReactBootStrap.Nav>
    <ReactBootStrap.Form onSubmit={this.onSubmitSymbol} inline>
      <ReactBootStrap.FormControl type="text" name="enteredSymbol" onChange={this.changeInput} placeholder="Enter Stock Symbol" className="mr-sm-2" />
      <ReactBootStrap.FormControl type="submit" value="Search"/>
    </ReactBootStrap.Form>
  </ReactBootStrap.Navbar>
  <br />


                <div>
                          <ReactBootStrap.Container>
  <ReactBootStrap.Row>
    <ReactBootStrap.Col>
        <ReactBootStrap.Card style={{ width: '18rem' }}>

                            <ReactBootStrap.Card.Body>
                                <ReactBootStrap.Card.Title>{this.state.stockName}</ReactBootStrap.Card.Title>
                                </ReactBootStrap.Card.Body>
                                    <ReactBootStrap.ListGroup className="list-group-flush">
                                        <ReactBootStrap.ListGroupItem >Current price: { this.state.currentPrice}</ReactBootStrap.ListGroupItem>
                                        <ReactBootStrap.ListGroupItem>Low price: { this.state.lowPrice}</ReactBootStrap.ListGroupItem>
                                        <ReactBootStrap.ListGroupItem>High price: { this.state.highPrice}</ReactBootStrap.ListGroupItem>
                                    </ReactBootStrap.ListGroup>
                                    <ReactBootStrap.Card.Body>
                                    <ReactBootStrap.Button onClick={ this.buyStock } variant="dark">Buy Share</ReactBootStrap.Button>
                                {/* <ReactBootStrap.Card.Link href="#">Another Link</ReactBootStrap.Card.Link> */}
                                </ReactBootStrap.Card.Body>
                            </ReactBootStrap.Card>
                        </ReactBootStrap.Col>
    <ReactBootStrap.Col> 
        <ReactBootStrap.Card className="circle">
                                       <ReactBootStrap.Card.Title>User: ${ this.state.accountBalance }</ReactBootStrap.Card.Title>
                                       <ReactBootStrap.Card.Title>shares: { this.state.stockShares }</ReactBootStrap.Card.Title>
                                     </ReactBootStrap.Card>
                                     </ReactBootStrap.Col>
                            </ReactBootStrap.Row>
            </ReactBootStrap.Container>

                    <div>




                                    {/* <h2> {this.state.stockName}</h2>
                                     <p>Current price: { this.state.currentPrice}</p>
                                <p>Low price:{this.state.lowPrice}</p>
                                    <p> High price: {this.state.highPrice}</p> */}



                    </div>


                </div>





            </div>
        )
    }
}

【问题讨论】:

    标签: javascript node.js reactjs mongodb mongoose


    【解决方案1】:

    我认为你有很多无关的代码,但跳出来的是你的getUserInfo 函数。不要覆盖整个 this.state.user 对象,而是保留前一个对象并仅覆盖您想要更改的内容 -

    getUserInfo = () => {
      axios.get('/api/user').then((response) => {
        this.setState(prevState => ({
          user: {
            ...prevState.user,
            accountBalance: response.data.accountBalance,
          }
        }))
      })
    }
    

    【讨论】:

    • 我知道我在这个特定组件中有很多我不需要或没有意义的代码,但我确实有一个用户组件,如果这有意义我想导入该帐户来自该组件的平衡用户数据和导入能够存储来自渲染股票的信息,但在我的开发人员工具中的组件中注意到对象是匿名的{ this.state.stockShares }{this.state.accountBalance}
    猜你喜欢
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 2018-12-29
    • 2022-01-16
    • 1970-01-01
    • 2019-10-28
    • 2019-08-10
    • 1970-01-01
    相关资源
    最近更新 更多