reactjs - app从api获取数据后不会改变状态

问题描述 投票:1回答:1

我正在构建一个从News API获取数据的React新闻应用程序。在主页上,我有一个搜索栏,用户可以在其中输入要从API中检索的关键词。当我输入关键字并按Enter键时,状态会发生变化,结果在页面上可见,但随后会立即刷新并显示默认页面。

App.js:

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { articles: [], keyword: ''};
    this.fetchNewsWithKeywords = this.fetchNewsWithKeywords.bind(this);
  }



  fetchNewsWithKeywords(keyword){
    searchForKeywords(keyword)
    .then(articles => this.setState({ articles: articles, keyword: keyword}))
  }

  render() {
    return (
      <Router >
      <div className="App">
        <div className="container" >
          <Header/>
          <Route exact path="/" render={props => (

            <React.Fragment>
              <SearchNews fetchNewsWithKeywords = {this.fetchNewsWithKeywords.bind(this)}/>
              <NewsList articles = {this.state.articles}/>
            </React.Fragment>
          )} />
          <Route path="/top-headlines" component={TopHeadlines} />
          <Route path="/newest" component={Newest} />
        </div>
      </div>
      </Router>
    );
  }
}

export default App;

SearchNews.js

class SearchNews extends Component {
  state = {
    value: ""
  }
  onSubmit = (e) => {
    var str   = this.state.value;
    this.props.fetchNewsWithKeywords(str)
  }
  handleOnChange = event => {
    this.setState({
      value: event.target.value
    })
  };  
  render() {
    const { classes } = this.props;
    return (
      <form className={classes.container} noValidate autoComplete="off" onSubmit={this.onSubmit}>
        <TextField
        id="outlined-search"
        label="Search"
        type="search"
        className={classes.textField}
        margin="normal"
        variant="outlined"
        onChange={this.handleOnChange}
      />
      </form>
    )
  }
}

用于从API检索数据的函数

export async function searchForKeywords(keyword){
    var query = keyword


    var url = "https://newsapi.org/v2/everything?q="+ 
    encodeURIComponent(query) + 
    "&apiKey="+API_KEY;
    let result = await fetch(url).then(response => response.json());
    return result.articles.slice(0,20);

NewsList.js

export class NewsList extends Component {

  render() {
    return this.props.articles.map((article) => (
        <div className="gridContainer">
            <div className="gridItem" >
                <Article article = {article}/>
            </div>
        </div>
    ));
  } 
}

export default NewsList

Article.js

class Article extends Component {

  render() {
    const {
        title,
        description,
        publishedAt,
        source,
        urlToImage,
        url
      } = this.props.article;
      const { classes } = this.props;
      let date = new Date(publishedAt).toLocaleString();
    return (
      <Card className={classes.card} >
        <CardActionArea href={url} target="_blank">
            <CardMedia
                className={classes.media}
                image={urlToImage}
                title={title}
            />
            <CardContent >
                <Typography gutterBottom variant="h5" component="h2">
                {title}
                </Typography>
                <Typography component="p">
                {description}
                </Typography>
                <Typography variant="caption">
                {source.name}
                </Typography>
                <Typography variant="caption">
                {date}
                </Typography>
            </CardContent>
        </CardActionArea>
      </Card>
);
  }
}

export default withStyles(styles)(Article);
javascript reactjs callback
1个回答
0
投票

我认为你的问题在这里:

let result = await fetch(url).then(response => response.json());
return result.articles.slice(0,20);

你正在等待获取,然后.then得到json的响应,但是,你在results.articles.slice解决之前返回response.json()

尝试:

let result = await fetch(url)
result = await result.json()
return result.articles.slice(0,20);
© www.soinside.com 2019 - 2024. All rights reserved.