React Redux:如何在React Redux中更新投票计数。 一个React js等效项已被回答
下面的代码旨在更新投票系统。通过在页面加载时显示结果可以很好地工作。
这是我的问题:每当分别单击“ Upvote Vote”和“ Down Vote”按钮时,我需要更新每个用户的upvote和downvote。
但是,当我单击任一Upvote por down投票按钮时,Reducer下方出现错误
Uncaught (in promise) ReferenceError: items1 is not defined.
此错误在以下时间触发 用于在常量 VOTE_SUCCESS_POST
上发送投票和反对票的减速器部分在后端,我有php代码,可按如下所述返回数组数据。
有人可以帮助我显示数组值并根据用户投票方式将其更新(例如,投票赞成11和投票赞成7)吗?
<?php
// Update user response on a post
$return_arr[]= array("upvote"=>"11", "downvote"=>"7");
echo json_encode($return_arr);
exit;
?>
这是API调用返回的数组
[{"upvote":"11", "downvote":"7"}]
这是代码
import React from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { vActions } from '../_actions';
class VoteApp extends React.Component {
constructor(props) {
super(props);
this.state = {
us: 0
};
}
componentDidMount() {
this.props.dispatch(userActions.getVote());
}
handleupvote(person_id,person_vote) {
return (e) => this.props.dispatch(userActions.vote(person_id,person_vote));
}
handledownvote(person_id,person_vote) {
return (e) => this.props.dispatch(userActions.vote(person_id,person_vote));
}
render() {
const { post1, posts1 } = this.props;
return (
<div style={{background:'red'}} className="well col-md-12">
<p>Vote System in React Redux</p>
{posts1.items1 &&
<ul>
{posts1.items1.map((post1, index1) =>
<li key={post1.id}>
{post1.name} -- (Upvote: {post1.upvote})-- (downvote: {post1.downvote})
<br />
<input type="button" value="upvote" onClick={this.handleupvote(post1.id,1)} />
<input type="button" value="downvote" onClick={this.handledownvote(post1.id,1)} />
</li>
)}
</ul>
}
</div>
);
}
}
function mapStateToProps(state) {
const { posts1} = state;
const { post1 } = state;
return {
post1,
posts1
};
}
const connectedVoteApp = connect(mapStateToProps)(VoteApp);
export { connectedVoteApp as VoteApp };
这是我的减速机
import { userConstants } from '../_constants';
export function posts1(state = {}, action) {
switch (action.type) {
case userConstants.GETALL_REQUEST:
return {
// ...state,
loading: true
};
case userConstants.GETALL_SUCCESS:
return {
loading: false,
error: null,
items1: action.posts1
};
case userConstants.GETALL_FAILURE:
return {
error: action.error
};
// Reducer section for Sending upvote and down vote
case userConstants.VOTE_REQUEST_POST:
return {
...state,
items1: state.items1.map(post1 =>
post1.id === action.id
? { ...post1}
: post1
)
};
case userConstants.VOTE_SUCCESS_POST:
return {
...state,
items1: state.items1.map(post1 => {
if (post1.id !== action.id) {
//return { ...post1, upvote: action.posts1.items1[0].upvote, downvote: action.posts1.items1[0].downvote };
return { ...post1, upvote: items1[0].upvote, downvote: items1[0].downvote };
}
//return post1;
})
};
case userConstants.VOTE_FAILURE_POST:
return {
error: action.error
};
default:
return state
}
}
答案 0 :(得分:0)
这是解决我的问题的原因。由于返回的json数据位于数组中。 items1:action.posts1 [0] .upvote
谢谢