【问题标题】:React - calling the same function from separate onSubmit and onClick eventsReact - 从单独的 onSubmit 和 onClick 事件调用相同的函数
【发布时间】:2021-03-14 22:02:59
【问题描述】:

我在将 React 中的异步函数调用到外部 API 时遇到问题,我希望从两个单独的事件、表单的 onSubmit 和单独搜索结果的 onClick 调用该函数。

我有以下 React 组件:

App.js:

import React, { useState, useEffect } from 'react'
import './App.css';
import Ticker from './compoments/Ticker'
import SearchTicker from './compoments/SearchTicker'
import TickerResults from './compoments/TickerResults'
import SearchCompanyProfile from './compoments/SearchCompanyProfile';

function App() {
  const [company, setCompany] = useState([])
  const [price, setPrice] = useState([])
  const [symbol, setSymbol] = useState([])

     async function fetchCompanyProfile(e) {
      let company = '';
      if(e.target.target.ticker.value){
        company = e.target.ticker.value
        } else {
        company = e.target.innerHTML;
        } 
      console.log(company)
      e.preventDefault() 
      e.target.reset()
        const companyData = await fetch(https://someapicompany.com/profile/${company}?apikey=xyz)
          .then(res => res.json())
          .then(data => data)
            setCompany({data: companyData})
    }

    console.log(company.data)
 
  return (
    <div className="App">
        <SearchTicker getTicker={fetchTicker}/>
        <SearchCompanyProfile getCompanyProfile={fetchCompanyProfile}/>
        <TickerResults ticker={symbol} getTicker={fetchCompanyProfile}/>
        <CompanyProfile company={company}/>
    </div>
  );
}

export default App;

SearchCompanyProfile.js

import React from 'react'

const SearchCompanyProfile = (props) => {

    return (
        <div>
             <form onSubmit={props.getCompanyProfile} >
                <input type="text" name="ticker" placeholder="Enter Ticker..."/>
                <button value="Search" type="submit">
                Search
                </button>
            </form>
        </div>
    )
}

export default SearchCompanyProfile;

SearchTicker.js

import React from 'react'

const SearchTicker = (props) => {


    return (
        <div>
            <form onSubmit={props.getTicker}>
                <input type="text" name="symbol" placeholder="Enter Compamy Name..."/>
                <button value="Search" type="submit">
                Search
                </button>

            </form>
        </div>
    )
}

export default SearchTicker;

TickerResults.js

import React from 'react'

const TickerResults = (props) => {
    console.log(props)
    return (
        <div>
            {props.ticker.data && props.ticker.data.map(x => <p name="ticker" value={x.symbol} onClick={props.getTicker}>{x.symbol}</p>)}
        </div>
    )
}

export default TickerResults;

我的目标是通过提交 SearchCompanyProfile 表单和单击tickerResults 组件中的代码来调用异步函数fetchCompanyProfile。

我都试过了:

async function fetchCompanyProfile(e) {
      let company = '';
      if(e.target.ticker.value){
        company = e.target.ticker.value;
        } else {
        company = e.target.innerHTML;
        } 
      console.log(company)
      e.preventDefault() 
      e.target.reset()
        const companyData = await fetch(https://someapicompany.com/profile/${company}?apikey=xyz)
          .then(res => res.json())
          .then(data => data)
            setCompany({data: companyData})
    }

    console.log(company.data)

-和-

async function fetchCompanyProfile(e) {
      let company = '';
      if(e.target.innerHTML){
        company = e.target.innerHTML;
        } else {
        company = e.target.ticker.value;
        } 
      console.log(company)
      e.preventDefault() 
      e.target.reset()
        const companyData = await fetch(https://someapicompany.com/profile/${company}?apikey=xyz)
          .then(res => res.json())
          .then(data => data)
            setCompany({data: companyData})
    }

    console.log(company.data)

在这两种情况下,如果正确的事件以正确的顺序发生,它就会起作用,但在第一种情况下,如果我通过tickerResults 组件使用onClick 事件,我会遇到“值不能在未定义的情况下运行”,而在第二种情况下, innerHTML 只是来自 searchCompanyProfile 表单的表单输入,因此不会使用正确的值调用 fetch。

我知道这是一个冗长的问题,但任何建议都将不胜感激。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    这是异步/等待解决方案:

    async function fetchCompanyProfile(e) {
          let company = '';
          if(e.target.innerHTML){
            company = e.target.innerHTML;
            } else {
            company = e.target.ticker.value;
            } 
          console.log(company)
          e.preventDefault() 
          e.target.reset()
          let companyData = await fetch(https://someapicompany.com/profile/${company}?apikey=xyz)
          setCompany({data: companyData.json()})
        }
    

    【讨论】:

    • 感谢您的回复!
    【解决方案2】:

    你需要在 then 内部调用 setCompany({ data }) 因为它是承诺

    function App() {
      const [company, setCompany] = useState([]);
      const [price, setPrice] = useState([]);
      const [symbol, setSymbol] = useState([]);
    
      function fetchCompanyProfile(e) {
        let company = '';
        if(e.target.target.ticker.value){
          company = e.target.ticker.value
        } else {
          company = e.target.innerHTML;
        }
        console.log(company);
        e.preventDefault();
        e.target.reset();
        fetch('https://someapicompany.com/profile/${company}?apikey=xyz')
          .then(res => res.json())
          .then(data => {
            setCompany({ data })
          });
    
      }
    
      console.log(company.data)
    
      return (
        <div className="App">
          <SearchTicker/>
          <SearchCompanyProfile getCompanyProfile={fetchCompanyProfile}/>
          <TickerResults ticker={symbol} getTicker={fetchCompanyProfile}/>
          <CompanyProfile company={company}/>
        </div>
      );
    }

    【讨论】:

    • 感谢您的回复!
    • 如果答案正确,请在您的情况下将其设置为解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    • 2023-03-18
    • 1970-01-01
    相关资源
    最近更新 更多