0
我是新來的redux.I知道這是一個新手問題,但我找不到任何正確的解決方案。我建立簡單的帖子時,有人點擊 這是我的代碼 我的問題是如何更改或增加喜歡的特定職位數沒有變異狀態的,哪些是要做到這一點,當包含發佈照片如何增加郵政像沒有突變狀態在REDX?
的大數組對象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
}
}
感謝您的回答,但如果我添加不止一個帖子像按鈕似乎不工作'''未捕獲TypeError:無法讀取未定義(......)的屬性'id'''' – Nane
你能更新當前代碼嗎? – Thaadikkaaran
已更新我只是將我的代碼複製並粘貼到我的減速器中 – Nane