【问题标题】:How to Render API result to a Element?如何将 API 结果呈现给元素?
【发布时间】:2017-01-11 19:46:52
【问题描述】:

在函数handleExampleClick 中,我想用console.log(res.body.matches[i].id); 的结果更新App-menuViewer。现在我正在将信息记录到控制台。但我希望这些信息能够真正更新 app-menuviewer。我怎样才能做到这一点?如果您需要查看更多信息,repo 在这里:https://github.com/KanteLabs/Whats-Cookin/

function handleCookbookClick() {
    ReactDOM.render(
  <Cookbook />,
  document.getElementById('App-menuViewer')
);}


function handleExampleClick() {
  ReactDOM.render(
  request
  .get(searchRecipes)
  .query({ q: searchParameters2 }) // query string
  .type('json')
  .end(function(err, res){
    for(var i = 0; i < res.body.matches.length;i++){
      console.log(res.body.matches[i].id);
    }
  }),
    document.getElementById('App-menuViewer')
);}



class App extends Component {
  render() {
    return (
    <div className="App">
        <div className="App-header">
            <img src={logo} className="App-logo" alt="logo" />
            <h2>"What's Cookin'"</h2>
      <input className="searchBox" placeholder="search something"/>
            <button onClick={handleExampleClick}>Example</button>
    </div>      
    <div id="App-menu">
            <button onClick={handleCookbookClick}>Cookbook</button>
            <button>Recommendations</button>
            <button>Shopping List</button>
            <button>Search Options</button>
    </div>
        <div id="App-menuViewer"></div>
        <div className="App-SearchResults">
          <p>{ingredients}</p>
        </div>
    </div>
    );
  }
}

export default App;

【问题讨论】:

  • 将您的值存储在变量中并使用innerHTML 填充元素上的值
  • 那么代码会是这样吗? document.getElementById('App-menuViewer').innerHTML(recipeName)
  • 不——应该是这样的document.getElementById('App-menuViewer').innerHTML = recipeName;
  • 非常感谢!这有效并解决了我正在发生的问题。
  • 您介意我将此作为答案并接受吗? :)

标签: javascript ajax api reactjs web-applications


【解决方案1】:

将此作为所有者同意的答案:)

回答

将您的值存储在变量中并使用 innerHTML 填充元素上的值

示例

var recipeName = "";


....
.end(function(err, res){
 for(var i = 0; i < res.body.matches.length;i++){
    recipeName += res.body.matches[i].id; //assuming that its a string value      
 }
}),

document.getElementById('App-menuViewer').innerHTML = recipeName;

....

【讨论】:

    猜你喜欢
    • 2014-02-19
    • 1970-01-01
    • 2019-04-07
    • 2021-10-09
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    相关资源
    最近更新 更多