繁体   English   中英

JavaScript .map 未在 React 中呈现 chrome.topSites

[英]JavaScript .map not rendering chrome.topSites in React

我正在尝试从 Chrome 的 topSites api 为 chrome 扩展程序呈现标题列表。

当我将它登录到控制台时,我得到了这个:

[
  {
    "title": "Chrome Web Store",
    "url": "https://chrome.google.com/webstore?hl=en"
  }
]

但是,以下内容不会向页面呈现任何内容

render() {
  return (
    <ul>
      {
        chrome.topSites.get(data => {
          console.log(data);

          data.map(site => {
            return (
              <li key={site.title}>
                {site.title}
              </li>
            );
          });
        })
      }
    </ul>
  );
}

预期输出:带有站点标题的p标签呈现在屏幕上

实际输出:屏幕上没有呈现任何内容

这最终对我有用。 chrome.topSites.get into移动chrome.topSites.get into componendDidMount() and assigning it to state. Then mapping the and assigning it to state. Then mapping the this.state.sites` and assigning it to state. Then mapping the到渲染方法中的页面。

export default class TopSites extends Component {
  constructor(props) {
    super(props);

    this.state = {
      sites: [],
    }
  }

  componentDidMount() {
    chrome.topSites.get(data => {
      this.setState({
        sites: data
      });
    });
  }

  render() {
    const {sites} = this.state;

    return (
      <ul>
        {sites.map(site => {
          return (
            <li key={site.title}>
              {site.title}
            </li>
          );
        })}
      </ul>
    );
  }
}
state= {
  data: '',
 }

// declaring a async function 
getData = async () => {
        const result = await chrome.topSites.get(); // waiting for the result
 this.setState({ data: result});
 }

componentDidMount(){
  this.getData();
}


 render(){
 const list = this.state.data ? this.state.data.map((val) => <li key={val.title}> {val.title}
    </li> : null)
return(
     <ul>
     {list}
    </ul>

 )
}

暂无
暂无

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

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