【问题标题】:How to use react faq component with data from API如何将 React faq 组件与来自 API 的数据一起使用
【发布时间】:2020-09-29 16:33:32
【问题描述】:

我在我的 React Js Web 应用程序中使用这个组件:https://www.npmjs.com/package/react-faq-component

const data = {
    title: "FAQ (How it works)",
    rows: [
        {
            title: "Lorem ipsum",
            content: "Dolor sit amet",
        },
    ],
};

我需要用我的 API 检索到的数据填充“行:”。

这是我的代码:

class Faqs extends Component {
  constructor() {
    super()
    this.state = {
      faqs: []
    }
  }

  componentDidMount() {
    let category = 'caategory1';
    axios.get('https://myurl/api/faqs/'+category).then(response => {
      this.setState({
        faqs: response.data
      })
    })
  }

  render () {
    const { faqs } = this.state;
    const styles = {
      titleTextColor: "black",
      rowTitleColor: "black",
      rowContentColor: 'grey',
    }
    const config = {
      animate: true,
    }

    let data = {
      title: 'FAQS (How it works)',
      rows: [
        // Here is where I'm trying to print the json data from the API
        faqs.map(
            (faq, index) => {
                return (
                    `{title: ${faq.title}, content: ${faq.content}},`
                )
            }
        )
      ]
    }
}

我想这与转义有关,但我是 React 的初学者,所以如果有人能提供帮助,我将不胜感激。

谢谢!

【问题讨论】:

    标签: javascript reactjs jsx


    【解决方案1】:

    您的渲染语句永远不会返回。此外,您永远不会导入您说您尝试使用的常见问题解答组件。最后,你可能need to stabilize the value of "this"

    总而言之,代码会是这样的(还没有测试过):

    import React, { Component } from "react";
    import Faq from "react-faq-component";
    import axios from 'axios';
    
    const styles = {titleTextColor: "blue", rowTitleColor: "blue"};
    const config = {};
    
    export default class App extends Component {
      constructor() {
        super()
        this.state = {
            faqs: []
        }
      }
    
      componentDidMount() {
        let category = 'caategory1';
        let me = this;
        axios.get('https://myurl/api/faqs/'+category).then(response => {
          //Using "me" because I think "this" refers to the axios object
          me.setState({
              faqs: response.data
          })
        })
      }
      render() {
        return (
            <div>
                <Faq data={this.state.faqs} styles={styles} config={config} />
            </div>
        );
      }
    }
    
    

    【讨论】:

    • 不,我的朋友,"rows:" 需要像这样填充:rows: [ { title: "Lorem ipsum", content: "Dolor sit amet", }, ]。我只是贴了一部分代码,当然我已经导入了 axios 和 faq 组件。
    猜你喜欢
    • 1970-01-01
    • 2021-10-23
    • 2014-09-15
    • 2019-07-31
    • 1970-01-01
    • 2021-04-07
    • 2019-10-11
    • 1970-01-01
    • 2019-04-29
    相关资源
    最近更新 更多