gpt4 book ai didi

javascript - fetch 不应该在操作中 || reducer ?

转载 作者:行者123 更新时间:2023-11-30 15:52:24 25 4
gpt4 key购买 nike

  1. 如果我将 fetch 放在 componentDidMount () 中,我做对了吗?将 fetch 放入 action 或 reducer 中是愚蠢的做法吗?
  2. 为什么这个 {this.props.data.name} 在没有为 reducer 中的数据设置标准参数的情况下不起作用?没有这个 (state = {data: { }}, action)?!

reducer

const reducer = (state = {
data: {

}
}, action) => {
switch (action.type) {
case 'EXPERIMENT':
return {
...state,
data: action.data
}
break
default:
return state
}
}

export default reducer

组件

import React, { Component } from 'react'

import { connect } from 'react-redux'

class Persistent extends Component {
componentDidMount () {
fetch('https://api.github.com/users/reactjs').then((response) => {
response.json().then((json) => {
this.props.dispatch({
type: 'EXPERIMENT',
data: json
})
})
})
}
render () {
return (
<div>
<ol>
<li>{this.props.data.name}</li>
<li>{this.props.data.url}</li>
</ol>
</div>
)
}
}

export default connect(
(state) => {
return {
data: state.data
}
}
)(Persistent)

最佳答案

使用redux-thunk中间件。它允许 Action 创建者返回函数而不是 Action 对象。这些函数被链接起来以对操作对象进行最终分派(dispatch)。

创建商店时,包括如下中间件:

import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import createLogger from 'redux-logger';
import RootReducer from '../reducers/rootReducer';

const loggerMiddleware = createLogger();

export function configureStore(initialState) {
return createStore(
RootReducer,
initialState,
applyMiddleware(
thunkMiddleware,
loggerMiddleware
));
}

使用 thunk 中间件的 action creator 示例:

getCards(email, token) {
return (dispatch, getStore) => {
dispatch(CardActions.getCardsRequest(email));
fetch(apiUrls.getCardsUrl + email, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Api-Key': token,
},
})
.then(response => {
return response.json().then(responseJson => {
return dispatch(CardActions.getCardsResponse(responseJson.postcards, response.status));
});
})
.catch(err => {
console.error(err);
});
};
}

关于javascript - fetch 不应该在操作中 || reducer ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39113569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com