简体   繁体   English

反应生命周期方法componentDidMount()不起作用

[英]React life-cycle method componentDidMount() not working

I am very new to React and currently working on this hackernews app.我对 React 非常陌生,目前正在开发这个hackernews 应用程序。 I am following the instructions given in the book "the road to learn react" to build this app.我正在按照“学习反应之路”一书中给出的说明来构建这个应用程序。 However, the react life-cycle method componentDidMount() does not seem to be working as the console.log inside it is not being displayed.但是,反应生命周期方法 componentDidMount() 似乎没有工作,因为它里面的 console.log 没有被显示。 I have followed every instruction properly and double checked them.我已正确遵循每条指令并仔细检查了它们。 Still, I am unable to figure out the reason.尽管如此,我仍然无法弄清楚原因。 Any help would be much appreciated.任何帮助将非常感激。

My App.js file's code:我的 App.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;

Note: Ignore the onDismiss() function, it still needs a work around.注意:忽略 onDismiss() function,它仍然需要解决。

Can you check the setSearchTopStories() function parameter.你能检查一下setSearchTopStories() function 参数吗? Why do you restructure the result parameter?为什么要重构result参数?

Try this instead:试试这个:

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

Make sure that some other code is actually creating your App class.确保其他一些代码实际上正在创建您的App class。 Putting console.log inside the constructor should help You with this.console.log放在constructor中应该可以帮助您解决这个问题。

The code You are searching for should looks like this:您正在搜索的代码应如下所示:

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

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM