【发布时间】:2017-08-20 19:57:43
【问题描述】:
我创建了组件并使用 connect() 像这样连接它:
function mapStateToProps(state) {
return { users: state.users.users }
}
function mapDispatchToProps(dispatch) {
return { userActions: bindActionCreators(UserActions, dispatch) }
}
export default connect(mapStateToProps, mapDispatchToProps)(Test)
遗憾的是,当我在 chrome 中打开 React 工具时,我得到了这个: 更改状态不会强制组件更新。为什么它不订阅它?
编辑:
我正在通过动作创建器和减速器更改状态。看起来是这样的:
export function addUser(user) {
return function (dispatch) {
axios.post('http://localhost:4200/users/add/user', {user:user})
.then(() => dispatch({
type: USER_ADD,
user: user
})).catch(err => console.log(err));
}
}
export function getUsers() {
return function (dispatch) {
axios.get('http://localhost:4200/users')
.then((response) => dispatch({
type: REQUEST_USERS,
users:response.data
})).catch(err => console.log(err));
}
}
和减速器:
export function users(state = initialState, action) {
switch (action.type) {
case 'USER_ADD':
{
return {
...state,
users: [
...state.users,
action.user
]
}
break;
}
case 'REQUEST_USERS':
{
return {
...state,
users: [
action.users
]
}
break;
}
.........
这是我的完整组件:
class Test extends Component {
constructor(props) {
super(props);
this.state = {
login: "",
password: ""
}
}
handleLoginInputChange = (e) => {
this.setState({login: e.target.value})
}
handlePasswordInputChange = (e) => {
this.setState({password: e.target.value})
}
handleSubmit = (e) => {
e.preventDefault()
let user = {login:this.state.login,
password:this.state.password,userId:Math.floor(Math.random()*(100000))};
this.props.userActions.addUser(user);
}
render() {
return (
<div className="test">
<form>
<input type="text" onChange={this.handleLoginInputChange} value=
{this.state.login} placeholder="login"/>
<input type="text" onChange={this.handlePasswordInputChange}
value={this.state.password} placeholder="pass"/>
<button onClick={this.handleSubmit}>send</button>
</form>
<UsersList users = {this.props.users} />
</div>
)
}
componentDidMount() {
this.props.userActions.getUsers();
}
}
function mapStateToProps(state) {
return { users: state.users.users }
}
function mapDispatchToProps(dispatch) {
return { userActions: bindActionCreators(UserActions, dispatch) }
}
export default connect(mapStateToProps, mapDispatchToProps)(Test)
我已将所有内容添加到 github,以便您可以看到它github。
您可能感兴趣的是 reducers/users.js、actions/useractions 和 components/Test.js。
我尝试了许多不同的方法。现在我在添加新用户后放弃了更改状态。而不是我制作了可以从服务器获取数据的按钮 - 它正在重新加载页面,所以我对该解决方案不满意
【问题讨论】:
-
你是如何改变 redux 状态的?通过动作调度和reducer?请发布更多代码。
-
你的组件已连接,显示其他代码,
-
点击
send时会发生什么。 AJAX 请求完成后,是否有动作被分派?因此,商店如何被修改?
标签: reactjs redux react-redux