reactjs - MapActionToProps 未更新商店
问题描述
我正在尝试更新我的商店,但它不会自动更新。
在不使用 dispatch 函数的情况下不调用MapActionToProps
更新 store。
请帮忙。是什么,我在这里做错了。
这是我的App.js
文件:
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { connect} from 'react-redux';
import { updateUser } from './actions/users-actions';
class App extends Component {
constructor(props){
super(props);
this.onUpdateUser = this.onUpdateUser.bind(this);
}
onUpdateUser(){
this.props.onUpdateUser('Sammy');
}
render() {
console.log(this.props);
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<button onClick={this.onUpdateUser}> Update User</button>
{this.props.user}
</div>
);
}
}
const mapStateToProps = state => ({
products : state.products,
user : state.user,
})
const mapActionsToProps = {
onUpdateUser : updateUser
};
export default connect(mapStateToProps,mapActionsToProps)(App);
这是我的Action File
:
export const UPDATE_USER = 'users:updateUser';
export function updateUser(newUser){
return{
type:UPDATE_USER,
payload:{
user:newUser
}
}
}
这是我的Reducer File
:
import { UPDATE_USER } from '../actions/users-actions';
export default function usersReducer(state='',type,payload){
switch(type){
case 'UPDATE_USER':
return payload.user;
default:
return state
}
}
我需要调用store.dispatch()
方法吗?
解决方案
dispatch
如果不调用组件中的函数,你真的无法做你想做的事。在您的情况下,当您尝试同时从组件上的 Redux 获取state
和制作dispatch
时 - 您需要通过以下方式dispatch
直接调用 from mapActionsToProps
:
const mapActionsToProps = dispatch => ({
onUpdateUser: (yourData) => dispatch(updateUser(yourData));
});
这对你有用。
而且您还需要更新您的Action
:
export const UPDATE_USER = 'users:updateUser';
export function updateUser(newUser) {
return {
type: UPDATE_USER,
newUser
}
}
还有Reducer
:
import { UPDATE_USER } from '../actions/users-actions';
export default function usersReducer(state = '', action){
switch(action.type){
case 'UPDATE_USER':
return action.newUser;
default:
return state
}
}