我对React非常陌生,目前正在开发此hackernews应用程序。我正在按照“学习的反应之路”一书中给出的说明来构建此应用。但是,由于未显示其中的console.log,因此反应生命周期方法componentDidMount()似乎不起作用。我正确地遵循了每条说明,并仔细检查了它们。不过,我仍然无法找出原因。任何帮助将不胜感激。
我的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;
注意:忽略onDismiss()函数,它仍然需要解决。
答案 0 :(得分:-1)
请确保其他一些代码实际上正在创建您的App
类。
将console.log
放在constructor
内应该可以帮助您。
您要搜索的代码应如下所示:
ReactDOM.render(<App />, document.getElementById("root"));