简体   繁体   English

如何使用 Axios 在 React 中实现 onClick componentDidMount()

[英]How to implement onClick componentDidMount() in React using Axios

I am trying to make a movie search function using React, Axios, and movieDB API.我正在尝试使用 React、Axios 和 movieDB API 进行电影搜索 function。 The functionality I am trying to implement right now is typing in a movie into the search bar and clicking the submit button will return the movie title as an H1 element.我现在尝试实现的功能是在搜索栏中输入电影,然后单击提交按钮会将电影标题作为 H1 元素返回。

My onClick function does not work: <button onClick={(e)=>clickHandler()}>submit</button>我的 onClick function 不起作用: <button onClick={(e)=>clickHandler()}>submit</button>

componentDidMount() will work only when the page refreshes and you cannot search for anything as the submit button is broken. componentDidMount() 仅在页面刷新时起作用,并且由于提交按钮损坏,您无法搜索任何内容。

I am not sure how to implement this, but I would also not mind if I could get it to search by hitting enter instead of using a button, whichever is easier.我不确定如何实现这一点,但我也不介意是否可以通过按 Enter 键而不是使用按钮来搜索它,以更容易者为准。

Here is my code so far.到目前为止,这是我的代码。

App.js应用程序.js

import React from "react"
import Movielist from './components/Movielist'



function App() {
    return (
        <div>
            <input type="search" id="search" />
            <button onClick={(e)=>clickHandler()}>submit</button>
            <h1 id="title">title</h1>
            <Movielist />
        </div>

    )
}

export default App

Movielist.js电影列表.js

import React from 'react';

import axios from 'axios';

export default class Movielist extends React.Component {
  state = {
    title: ""
  }

    componentDidMount() {
    const API_KEY = '***********************';
    const query = document.getElementById('search').value;
    axios.get(`https://api.themoviedb.org/3/search/movie?api_key=${API_KEY}&query=${query}`)
      .then(res => {
        const title = res.data['results'][0]['title'];
        this.setState({ title });

      })

  }

  render() {
    return (

    <h1>{this.state.title}</h1>

    )
  }
}

index.js index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
    <App />,
    document.getElementById('root')
);
import React from 'react';

import axios from 'axios';

export default class Movielist extends React.Component {
  state = {
    title: ""
  }

    clickHandler = (event) => {
        if (event.keyCode === 13) {
           const query = event.target.value;
           const API_KEY = '***********************';
    axios.get(`https://api.themoviedb.org/3/search/movie?api_key=${API_KEY}&query=${query}`)
      .then(res => {
        const title = res.data['results'][0]['title'];
        this.setState({ title });

      })
        }
    }

  render() {
    return (

<input type="search" id="search" onKeyDown={event => this.clickHandler(event)} />
    <h1>{this.state.title}</h1>

    )
  }
}

If you want to query the API after user push submit button.如果您想在用户按下提交按钮后查询 API。 You should put your call to API in the call handler, then pass the state from App to MovieList as props您应该在调用处理程序中调用 API,然后将 state 作为道具从 App 传递给 MovieList

export class App extends React.Component {
    state = {
        title: ""
    }

    clickHandler() {
        const API_KEY = '***********************';
        const query = document.getElementById('search').value;
        axios.get(`https://api.themoviedb.org/3/search/movie?api_key=${API_KEY}&query=${query}`).then(res => {
            const title = res.data['results'][0]['title'];
            this.setState({ title });
        });
    }

    render() {
        return (
            <div>
                <input type="search" id="search" />
                <button onClick={(e)=>clickHandler()}>submit</button>
                <h1 id="title">title</h1>
                <Movielist list={this.state.title}/>
            </div>

        )
    }
}

export class MovieList extends React.Component {
    render() {
         <h1>{this.props.title}</h1>
    }
}

Alternatively, you can wrap the input in a element and use onSubmit + evt.preventDefault() instead, by doing so you can handle button click and pressing "Enter" to submit.或者,您可以将输入包装在一个元素中并使用 onSubmit + evt.preventDefault() 代替,这样做您可以处理按钮单击并按“Enter”提交。

You should call API to get the movie list after hitting the button, then pass the data that you've got to Movielist .点击按钮后,您应该调用 API 来获取电影列表,然后将您获得的数据传递给Movielist Try this:尝试这个:
In App.js :App.js

 import React from "react" import axios from 'axios' import Movielist from './components/Movielist' function App() { const [movieList, setMovieList] = React.useState([]) const handleOnSubmit = () => { const API_KEY = '***********************'; const query = document.getElementById('search').value; axios.get(`https://api.themoviedb.org/3/search/movie?api_key=${API_KEY}&query=${query}`).then(res => { const title = res.data['results'][0]['title']; setMovieList(res.data['results']) }) } return ( <div> <input type="search" id="search" /> <button onClick={handleOnSubmit}>submit</button> <h1 id="title">title</h1> <Movielist movieList={movieList}/> </div> ) } export default App

In Movielist.js :Movielist.js

 import React from 'react'; const Movielist = ({movieList}) => { return ( <div> { movieList.map(movie => <h1 key={movie.key}>{movie.title}</h1>) } <div/> ) } } export default Movielist

import React, {useState} from "react"
import axios from 'axios';
import Movielist from './components/Movielist'

const [title, setTitle] = useState("")
const API_KEY = '***********************'

function App() {

  const clickHandler = () => {
    const query = document.getElementById('search').value;
    axios.get(`https://api.themoviedb.org/3/search/movie?api_key=${API_KEY}&query=${query}`)
    .then(res => {
      const title = res.data['results'][0]['title'];
      setTitle(title);
    })

 }

    return (
        <div>
            <input type="search" id="search" />
            <button onClick={clickHandler}>submit</button>
            <h1 id="title">title</h1>
            <Movielist title={title} />
        </div>

    )
}

export default App

just move call api handle to your onclik func then pass title props to movie list只需将调用 api 句柄移动到您的 onclik func 然后将标题道具传递给电影列表

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

相关问题 在 componentDidMount() 中反应 Axios 调用 - React Axios call in componentDidMount() 使用 ComponentDidMount() 时不理解 400 错误 - React Axios - Do not understand 400 error when using ComponentDidMount() - React Axios React函数在componentDidMount上起作用,而不在onClick上起作用 - React function working on componentDidMount but not onClick 如何在 axios 和 React 中实现 DELETE 方法? - How to implement DELETE method in axios and React? 如何实现React + axios的长轮询 - How to implement long polling for React + axios 尝试在 React 中实现 Axios - Trying to implement Axios in React 如何在React中使用钩子实现componentDidMount以使其符合EsLint规则“ react-hooks / exhaustive-deps”:“ warn”? - How to implement componentDidMount with hooks in React to be in line with the EsLint rule “react-hooks/exhaustive-deps”: “warn”? 使用react componentDidMount在变量中未定义 - undefined in variable using react componentDidMount 在 ComponentDidMount 中反应 axios 请求不将数据作为道具传递给组件 - React axios request in ComponentDidMount not passing data as props to component 将有状态 React 组件转换为无状态功能组件:如何实现“componentDidMount”类型的功能? - Converting stateful React component to stateless functional component: How to implement "componentDidMount" kind of functionality?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM