gpt4 book ai didi

reactjs - Redux-thunk 调度不起作用

转载 作者:行者123 更新时间:2023-12-03 13:17:14 25 4
gpt4 key购买 nike

我正在研究 thunk 并试图弄清楚如何实现 api 调用。它不起作用,所以我又回到了最基础的地方。当我单击按钮时,它在控制台中显示“到达这里!”,但当我“console.log(dispatch)”时没有显示任何内容。我在这里遗漏了什么吗?

import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import { connect, Provider } from 'react-redux';
import thunk from 'redux-thunk'
import axios from 'axis';

const store = createStore(
reducer,
applyMiddleware(thunk)
);

function fetchUser() {
return axios.get('https://randomuser.me/api/');
}

function addUser() {
console.log('Getting here');
return (dispatch) => {
console.log(dispatch) //not showing anything
return fetchUser().then(function(data){
console.log(data);
});
};
}

class App extends React.Component {
addUser() {
addUser();
}

render() {
return (
<button onClick={this.addUser.bind(this)}>+</button>
)
}
}

const mapPropsToState = function(store){
return {
newState: store
}
}

var ConnectApp = connect(mapPropsToState)(App);

ReactDOM.render(
<Provider store={store}>
<ConnectApp />
</Provider>,
document.getElementById('app')
)

最佳答案

您不能从组件中将 addUser() 作为常规函数调用。您必须使用 mapDispatchToProps 函数并将其传递给您的 connect 调用,以便能够分派(dispatch) addUser()

const mapDispatchToProps = dispatch => ({addUser: () => dispatch(addUser())})

然后

ConnectApp = connect(mapPropsToState, mapDispatchToProps)(App);

现在您可以将其称为 Prop 。

addUser() {
this.props.addUser();
}

关于reactjs - Redux-thunk 调度不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41573643/

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