我是redux的新手。我知道这是一个新手问题,但我找不到任何正确的解决方案。我正在构建一个简单的帖子,当有人点击时 这是我的代码 我的问题是如何在不改变状态的情况下更改或增加特定帖子的喜欢数量以及在包含图片的帖子的大数组对象时最有效的方法
App.js
import React from 'react';
import {connect} from 'react-redux';
import uuid from 'uuid'
import * as inputActions from './actions/addinput';
class Main extends React.Component{
constructor(props){
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.handlelike = this.handlelike.bind(this);
}
handleSubmit(e){
e.preventDefault();
console.log(e.target.name.value)
this.props.addinput
(
{
id:uuid.v1(),
name:e.target.name.value,
likes:0
}
)
}
handlelike(id){
this.props.likes(id)
}
render(){
return(
<div>
<form onSubmit={this.handleSubmit}>
<input type="text" name="name"/>
<input type="submit"/>
</form>
<div>
{this.props.inputs.map((data) => {
return(
<div key={data.id}>
<p >{data.name} <button onClick={ () => this.handlelike(data.id)}> {data.likes} Like it</button></p>
</div>
)
})}
</div>
</div>
)
}
}
const mapStateToPros = (state) => {
return{
inputs:state.addinput
}
};
const mapDispatchToProps = (dispatch) => {
return {
addinput: input => dispatch(inputActions.postinput(input)),
likes:id => dispatch(inputActions.likes(id))
}
};
export default connect(mapStateToPros,mapDispatchToProps)(Main)
actions.js
import * as actionTypes from './actionTypes';
export const postinput = (input) =>{
console.log(input,"From Action")
return{
type:'POST_INPUT',
payload:input
}
}
export const likes = (id) => {
return{
type:'LIKES',
payload:id
}
}
reducers.js
export default (state = [],action) => {
switch (action.type){
case 'POST_INPUT':
return[
...state,
Object.assign({},action.payload)
];
case 'LIKES':
export default (state = [],action) => {
switch (action.type){
case 'POST_INPUT':
return[
...state,
Object.assign({},action.payload)
];
case 'LIKES':
//start work from here
return state.map((post) => {
console.log(post.id);
if (post.id === action.payload) {
return Object.assign({}, post, { likes: post.likes+1 })
} });
default:
return state
}
}
答案 0 :(得分:1)
如您所知,您不应该在redux中改变状态/存储,您可以返回新状态,如下所示,
case 'LIKES':
return state.map((post) => {
if (post.id === action.payload) {
return Object.assign({}, post, { likes: post.likes+1 }) }
}
return post
)