【发布时间】:2017-06-25 15:16:41
【问题描述】:
我对 react 和 redux 很陌生。 我正在尝试使用以下更新减速器中的状态。
export default function ReducersTodos(state = [], action) {
switch (action.type) {
case ADD_TODO:
state = [...state, {
id: state.length? state.length+1: 1,
text: action.value,
like: 0
}]
return state
break;
case ADD_LIKE:
state = state.map(todo => todo.id === action.id ? { ...todo, like: todo.like+1 } : todo)
return state
break;
case DIS_LIKE:
state = state.map(todo => todo.id === action.id ? { ...todo, like: todo.like-1 } : todo)
return state
break;
default:
return state
}
}
点赞组件
export class Like extends React.Component {
constructor(props){
super(props);
// This binding is necessary to make `this` work in the callback
this._handleClickAdd = this._handleClickAdd.bind(this);
this._handleClickSub = this._handleClickSub.bind(this);
}
_handleClickAdd = function(e) {
e.preventDefault();
this.props.addLike(this.props.task.id);
}
_handleClickSub = function(e) {
e.preventDefault();
this.props.disLike(this.props.task.id);
}
render() {
return (
<div>
Like {this.props.task.like}
<button className="btn btn-primary" onClick={this._handleClickAdd} {...this.props.task.like}>+</button>
<button className="btn btn-danger" onClick={this._handleClickSub} {...this.props.task.like}>-</button>
</div>
);
}
}
function mapDispatchToProps(dispatch) {
return {addLike: bindActionCreators(addLike, dispatch),
disLike: bindActionCreators(disLike, dispatch)}
}
//set props
const mapStateToProps = (state, ownProps) => ({todos : state.todos});
Like = connect(mapStateToProps, mapDispatchToProps)(Like)
当我尝试点击like 或dislike 按钮时。
它重新渲染了整个列表,UI 看起来很奇怪。
有没有办法只更新数组的一部分而不查看整个数组。
GitHubhttps://github.com/vinaypost/todos 上提供的工作代码
【问题讨论】:
-
“不查看整个数组”是什么意思。你的整个 UI 应该重新渲染是正确的,这就是 React 的工作方式。您可以阻止某些组件重新渲染,但这些是优化,您现在不必担心它。如果整个 UI 看起来很奇怪,那就是其他地方出了问题。你能添加一个 JSbin 或 Codepen 来说明问题吗?
-
我在
Codepen和JSbin上上传代码时遇到了一些困难。所以我已经将我的代码上传到 GitHub github.com/vinaypost/todos -
有谁知道如何制作稳定的用户界面。
标签: reactjs redux react-redux