React жизненный цикл метода componentDidMount () не работает - PullRequest
0 голосов
/ 27 мая 2020

Я новичок в React и сейчас работаю над этим приложением hackernews. Я следую инструкциям, данным в книге «Как научиться реагировать», чтобы создать это приложение. Однако метод componentDidMount () жизненного цикла реакции не работает, так как console.log внутри него не отображается. Я тщательно выполнил все инструкции и дважды их проверил. Тем не менее, я не могу понять причину. Любая помощь будет принята с благодарностью.

Мое приложение. js Код файла:

import React from 'react';
import './App.css';
const fetch=require("node-fetch");
const DEFAULT_QUERY='redux';
const PATH_BASE='https://hn.algolia.com/api/v1';
const PATH_SEARCH='/search';
const PARAM='query=';
//const url=`${PATH_BASE}${PATH_SEARCH}?${PARAM}${DEFAULT_QUERY}`

function isSearched(searchTerm){
  return function(item){
    return !searchTerm||item.title.toLowerCase().includes(searchTerm.toLowerCase());
  }
}

class App extends React.Component{

  constructor(props){
    super(props);
    this.state={
      result:null,
    searchTerm:DEFAULT_QUERY
    }

    this.fetchTopStories=this.fetchTopStories.bind(this);
    this.setSearchTopStories=this.setSearchTopStories.bind(this);
    this.onDismiss=this.onDismiss.bind(this);
    this.onSearchChange=this.onSearchChange.bind(this);
   }

  setSearchTopStories({result}){
    this.setState({result});
  }

   fetchTopStories(searchTerm){
   fetch(`${PATH_BASE}${PATH_SEARCH}?${PARAM}${searchTerm}`)
    .then(response=>response.json())
    .then(result=>this.setSearchTopStories(result));
  }


  onDismiss(id){
      const isNotId=item=>item.ObjectID!==id;
      const updatedList=this.state.list.filter(isNotId);
      this.setState({list:updatedList});
  }

  onSearchChange(event){

    this.setState({searchTerm:event.target.value});
  }

  componentDidMount(){ //NOT WORKING
    console.log("MOUNTED");
    const {searchTerm}=this.state;
    this.fetchTopStories(searchTerm);

  }

  render(){
    const {result,searchTerm}=this.state
    if(!result){return null;}
    return(
     <div className="page">
       <div className="interactions">

       <Search
        value={searchTerm}
        onChange={this.onSearchChange}
       >Search</Search>
       </div>

       <Table 
       list={result.hits}
       pattern={searchTerm}
       onDismiss={this.onDismiss}/>

    </div>
    );
  }

}

const Search=({value,onChange,children})=>{

  return(

    <form>
    {children}<input type="text"
      value={value}
      onChange={onChange}/>
    </form>
  )}


const Table=({list,pattern,onDismiss})=>
  <div className="table">
    {
        list.filter(isSearched(pattern)).map(item=>
        <div key={item.ObjectID} className="table-row">
          <span style={{width:'40%'}}>
            <a href={item.url}>{item.title}</a>
          </span>
          <span style={{width:'30%'}}>{item.author}</span>
          <span style={{width:'10%'}}>{item.comments}</span>
          <span style={{width:'10%'}}>{item.points}</span>
          <span style={{width:'10%'}}>
            <Button onClick={()=>onDismiss(item.ObjectID)}
            className="button-inline">Dismiss</Button>
          </span>
        </div>
      )
    }
    </div>


const Button=({onClick,className='',children})=>{

    return(
      <button
      type="button"
    onClick={onClick}
    className={className}>{children}</button>

    )
  }




export default App;

Примечание. Не обращайте внимания на функцию onDismiss (), она все еще требует работы.

1 Ответ

0 голосов
/ 27 мая 2020

Убедитесь, что какой-то другой код действительно создает ваш App класс. Помещение console.log внутри constructor должно помочь Вам в этом.

Код, который вы ищете, должен выглядеть так:

ReactDOM.render(<App />, document.getElementById("root"));
...