Почему функция карты не выполняет итерацию по массиву? - PullRequest
1 голос
/ 13 июля 2020

enter image description here

I am using React, which I am new to and it says to use the map method to iterate over the array. When I do that the entire array logs to the console and not the individual words I want.

I am trying to call stock symbols when a user types them in the text box. But under the function getSymbol() the state of symbol is still an array even when I used map in render. Can anyone point me in the right direction? Or what can I do to get single elements.

Here is my code:

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

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

    getSymbol = (e) => {
        e.preventDefault(),
            this.setState({
                symbol: this.state.symbol

            }, () => {
                console.log(this.state.symbol)
            })
    }

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


    render() {
        const { symbol, userInput } = this.state
        if (userInput === symbol) {
            return (

                symbol.map((symbol, i) => ({symbol.displaySymbol})),
                console.log('same')
            )
        } else {
            return (
                 Введите символ акции   Отправить   )}}} 

Ответы [ 2 ]

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

Проблема в вашем блоке if. Метод карты работает нормально. Что происходит, вы сравниваете userInput (String) с символом (массивом), он не будет работать. Я не знаю, какую проверку вы пытаетесь сделать. Но если нужно проверить, находится ли userInput в массиве, вы делаете это неправильно.

import React from "react";
class Symbol extends React.Component {
constructor(props) {
super(props);
this.state = {
  userInput: "",
  symbol: [],
  isFiltered: false,
  isLoaded: false,
 };
}

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

getSymbol = (e) => {
e.preventDefault();
const filter = this.state.symbol.filter(
  (el) => el.displaySymbol === this.state.userInput
);
// console.log(filter);
this.setState(
  {
    symbol: filter,
    isFiltered: true,
  },
  () => {
    console.log(this.state.symbol);
   }
 );
};

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

 render() {
 const { symbol, userInput } = this.state;
 //console.log(userInput);
 if (this.state.isFiltered) {
  return symbol.map((symbol, i) => {
    return (
      <span className="symbol" key={i}>
        {symbol.displaySymbol}
      </span>
    );
  });
} else {
  return (
    <div className="enterstock">
      <h1 className="title">Enter Stock Symbol</h1>
      <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>
  );
  }
 }
}
export default Symbol;
1 голос
/ 13 июля 2020

Вы используете symbol двумя разными способами, и они сталкиваются. Попробуйте переименовать параметр вашей функции map():

symbol.map((s, i) => (<span className="symbol" key={i}>{s.displaySymbol}</span>)),

symbol не является зарезервированным словом в JavaScript, так что у вас должно получиться хорошо.

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