首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在React js中的变量改变时重新加载api fetch调用?

如何在React js中的变量改变时重新加载api fetch调用?
EN

Stack Overflow用户
提问于 2020-07-01 23:47:19
回答 2查看 383关注 0票数 0

我正在使用Gutenberg Editor为Wordpress创建一个块,该编辑器正在使用React js。

因此,我使用与fetch()相同的apiFetch()调用Wordpress API

代码语言:javascript
复制
class PortfolioTagsEdit extends Component {
    constructor(props) {
        super(props);
        this.state = {
          data: [],
          isLoading: false,
        };
    }
    componentDidMount() {
        const { attributes } = this.props;
        const { switcher } = attributes;
        this.setState({ isLoading: true });
        apiFetch( { path: `/wp/v2/${switcher}?post` } )
          .then(data => this.setState({ data, isLoading: false }));
    }
 
  ...
}

对于变量switcher,我有控制器来改变这个值。

我的问题是,当我切换switcher的值时,我应该重新加载api调用,但我不知道如何重新加载)

你能帮帮我吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-07-01 23:57:20

要做到这一点,最简单的方法是在state中使用switcher变量。然后,您可以实现componentDidUpdate方法来调用apiFetch:

代码语言:javascript
复制
class PortfolioTagsEdit extends Component {
    constructor(props) {
        super(props);
        this.state = {
          data: [],
          isLoading: false,
          switcher: this.props.attributes.switcher
        };
    }

    componentDidMount() {
        this.callAPI()
    }

    componentDidUpdate(prevProps, prevState) {
       if (prevState.switcher !== this.state.switcher) this.callAPI();
    }
    
    callAPI() {
        const { switcher } = this.state;

        this.setState({ isLoading: true });

        apiFetch( { path: `/wp/v2/${switcher}?post` } )
          .then(data => this.setState({ data, isLoading: false }));
    }
    ...
}

查看componentDidUpdate - https://reactjs.org/docs/react-component.html#componentdidupdate的文档

您还可以了解如何使用挂钩(特别是useEffect -https://reactjs.org/docs/hooks-reference.html#useeffect )来完成此任务

票数 1
EN

Stack Overflow用户

发布于 2020-07-01 23:59:58

使用react钩子,您可以使用useEffect来获取API。

代码语言:javascript
复制
function PortfolioTagsEdit({ attributes }) {
    // state
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState([])

    // here useEffect will run on component mount and every-time attributes.switcher changes
    useEffect(() => {
        setLoading(true)
        apiFetch( { path: `/wp/v2/${switcher}?post` } )
          .then(data => {
              setLoading(false)
              setData(data)
          });
    }, [attributes.switcher]) 


    return (
     ....
    )
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62680567

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档