Как я могу получить доступ к массиву, если помещаю его в this.state? - PullRequest
0 голосов
/ 14 июля 2020

enter image description hereI am new to react and have read the react docs on how to make an Ajax call. They made it look so simple when they were returning the json information but it doesn't work for me. I am trying to call the json information and set it to this.state.stockSymbol but every time I try to access the information I use typeof and it returns an object. I can see the json information clearly when I console.log it but for some reason it won't update in my getSymbol function. I think it has to to with the async call but I'm not totally understanding it. Can someone point me in the right direction?

Here is my code:

class Stocks extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            userInput: '',
            stockSymbol: [],
            isLoaded: false
        }
    }

    typeSymbol = (e) => {
        this.setState({
            userInput: e.target.value.toUpperCase()
        }, (e) => {
            console.log(this.state.userInput)
        })
    }

    getSymbol = (e) => {
        e.preventDefault(),
            this.setState({
                stockSymbol: this.state.stockSymbol
            }, () => {
                console.log(typeof this.state.stockSymbol)
                console.log(this.state.stockSymbol)
            })
    }

    componentDidMount() {
        fetch(`https://finnhub.io/api/v1/stock/symbol?exchange=US&token=${key}`)
            .then(res => res.json())
            .then(
                (results) => {
                    this.setState({
                        isLoaded: true,
                        stockSymbol: results
                    });
                    console.log(results)
                },
                (error) => {
                    this.setState({
                        isLoaded: true,
                        error
                    });
                }
            )
    }


    render() {
        const { stockSymbol, userInput, results } = this.state


        stockSymbol.map((stock, i) => {

            if (userInput === this.state.stockSymbol) {
                return (
                    console.log('same'),
                    
                        {stock.displaySymbol}
                    
                );
            }
        })



        return (
             Введите символ акции  {this.state.userInput}   Отправить   )}} ReactDOM.render ( , document.getElementById ('root')) 

Ответы [ 2 ]

1 голос
/ 14 июля 2020

Есть несколько проблем, но не с получением данных.

  1. То, что вы пытаетесь сделать, это фильтровать символы акций, но вы сравниваете userInput с символом акций, а не с названием каждой акции
  2. getSymbol не требует setState, так как вы уже установили состояние после выборки данных.

Вот песочница, которую вы можете опробовать и которая делает именно то, что вы ищете: https://codesandbox.io/s/twilight-dream-jwe7g?file= / src / index. js Выполните поиск по «линне грэхэм», чтобы проверить

0 голосов
/ 14 июля 2020

Скорее всего, проблема в вашей функции рендеринга, отображение на самом деле не рендерится. Вы должны вернуть одно выражение jsx, которое содержит все.

    render() {
        const { stockSymbol, userInput, results } = this.state


        const symbols = stockSymbol.map((stock, i) => {
            // removed your if statement, it didn't make sense
            return (
              <span className="symbol" key={i} onSubmit={this.getSymbol}>
                 {stock.displaySymbol}
              </span>
            );
        })

        return (
          <>
            {symbols}
            <div className="enterstock">
                <h1 className="title">Enter Stock Symbol</h1>
                <span className="symbol">{this.state.userInput}</span>
                <form className="inputfields" onSubmit={this.getSymbol}>
                    <input type="text" className="symfields" name="symbolname" onChange={this.typeSymbol}></input>
                    <button type="submit" className="btn">Send</button>
                </form>
            </div >
          </>
        )

    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...