Axios、UseEffect、Redux

Axios, UseEffect, Redux

为什么这个useEffect会无限循环

useEffect(() => {
    async function fetchApi() {
        let res = await Axios.get(props.url + '/articles')
        props.loadArticles(res.data)
    }

    fetchApi()
})

知道组件一直连接到redux

const mapStateToProps = (state) => ({
    url: state.ApiReducer.url,
    articles: state.ApiStocksReducer.articles
})

const mapDispatchToProps = (dispatch) => ({
    loadArticles: (data) => dispatch(loadArticles(data)),
    updateSelectedArticle: (data) => dispatch(updateSelectedArticle(data)),
    updateGeneralArticle: (data) => dispatch(updateGeneralArticle(data))
})

export default connect(mapStateToProps, mapDispatchToProps)(Articles);

Conditionally firing an effect The default behavior for effects is to fire the effect after every completed render. That way an effect is always recreated if one of its dependencies changes.

However, this may be overkill in some cases. We don’t need to create a new subscription on every update, only if the source prop has changed.

To implement this, pass a second argument to useEffect that is the array of values that the effect depends on.

https://reactjs.org/docs/hooks-reference.html#conditionally-firing-an-effect

useEffect(() => {
    async function fetchApi() {
        let res = await Axios.get(props.url + '/articles')
        props.loadArticles(res.data)
    }

    fetchApi()
}, []);