gpt4 book ai didi

javascript - Redux Saga 未触发/api 未调用 - props 未定义

转载 作者:行者123 更新时间:2023-11-28 17:31:47 25 4
gpt4 key购买 nike

我正在学习 redux-saga,但在调用我的 api 时遇到问题。看来我的传奇没有被触发,我的 Prop 也没有定义。
我正在使用 fake-server 来模拟数据。我测试了服务器,它似乎在传奇之外运行良好。

我的代码如下所示:

UserView.js

const UserView = (props)  => {
const {user} = props;
return (
<Header as='h2'>{user.name}</Header>
);
}

export default UserView

actions.js

export function showUserRequest(){
return{
type: USER_REQUEST
}
}

export function showUserSuccess(user) {
return {
type: USER_SUCCESS,
payload: user
}
}

export function showUserError(error){
return{
type: USER_ERROR,
payload: error
}
}

reducer.js

export default function (state = initialState, action) {
switch(action.type){
case USER_REQUEST:
return{
...state,
requesting: true,
successful: false,
errors: []
}
case USER_SUCCESS:
return{
...state,
user: action.payload,
requesting: false,
successful: true,
errors: [],
}
case USER_ERROR:
return{
requesting: false,
successful: false,
errors: state.errors.concat[{
body: action.error.toString(),
time: new Date(),
}],
}
default:
return state;
}
}

user.js

class User extends Component {

constructor(props) {
super(props);
this.fetchUser = this.fetchUser.bind(this);
}

componentWillMount(){
this.fetchUser();
}

fetchUser(){
const { showUserRequest } = this.props;
return showUserRequest;
}

render() {
const user = this.props;
return (<UserView user = {user.user}/>);
}
}

function mapStateToProps(state) {
return {
user: state.user
};
}

export default connect(mapStateToProps, {showUserRequest})(User);

sagas.js

const api = 'http://localhost:8080/user';

function userRequestApi () {
return axios.get(api)
}


function* userRequestFlow() { //does not seem to get invoked
try {
const user = yield call(userRequestApi);
yield put(showUserSuccess(user))
} catch (error) {
yield put(showUserError(error))
}
}

function* userWatcher() { //seems to get invoked
yield takeLatest(USER_REQUEST, userRequestFlow);
}

export default userWatcher

indexSaga.js/indexReducer.js

export default function* IndexSaga() {
yield all([
SignupSaga(),
LoginSaga(),
UserSaga()
]);
}

const IndexReducer = combineReducers({
route: routerReducer,
form: formReducer,
user: userReducer
})

export default IndexReducer

似乎根本没有调用 userRequestFlow 函数。
我确信这只是一个愚蠢的菜鸟错误,但我就是无法弄清楚。
我做错了什么?

最佳答案

在您的user.js中,您需要定义mapDispatchToProps()并分派(dispatch)showUserRequest操作,如下所示:

     function mapDispatchToProps(dispatch) {
return {
dispatchUserRequest: () => dispatch(showUserRequest()),
};
}

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

然后当您希望分派(dispatch)操作时调用 this.props.dispatchUserRequest()。

关于javascript - Redux Saga 未触发/api 未调用 - props 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50206926/

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