[英]React Redux actions and reducer mapping error
我對使用Redux還是很陌生,我試圖將我的動作和reducer正確地綁定到另一個組件時遇到了問題。 因此,我只是嘗試一些簡單的操作,例如在帖子中添加評論。 用戶鍵入他們的名字,然后輸入他們的評論,我希望兩者都顯示。 我試圖找到在我的減速器中編寫此代碼的最佳方法。
這是我的行動
export const ADD_COMMENT = 'ADD_COMMENT';
export const addComment = (author, comment) => ({
type: ADD_COMMENT,
author,
comment
});
這是我的comment.js
import React from 'react';
import {connect} from 'react-redux';
import CommentForm from './comment-form';
export function Comments(props) {
const comments = props.comments.map((comment, index) => (
<li key={index}>
<div className="author">{comment.author} says:</div>
<div className="comment">{comment.comment}</div>
</li>
));
return (
<section>
<h2>Comments</h2>
{comments.length ? <ul>{comments}</ul> : <div>No comments</div>}
<h3>Add a comment</h3>
<CommentForm />
</section>
);
}
export const mapStateToProps = (state, props) => ({
comments: state.comments
});
export default connect(mapStateToProps)(Comments);
這是我的reducer.js
import {ADD_COMMENT} from './actions';
const initialState = {
comments: []
};
export default function(state = initialState, action){
if(action.type === ADD_COMMENT){
return Object.assign({}, state, {
comments: action.comments
});
}
return state;
}
我現在有這種方式,我在我的reducer的函數中得到了一個“無法讀取未定義的屬性映射。我嘗試將author:添加到我的初始狀態和author:action.author中,並且仍然是同一件事。所以我我知道我的問題與我如何編寫減速器有關。
以下解決方案將幫助您從reducer獲取注釋並將其呈現在組件中(如果您有可用注釋),否則將不顯示no comments
該解決方案通過對Comments.js,操作和Reducer中進行的所有更正解決了以下問題
無法讀取未定義的屬性映射
嘗試添加注釋id作為li元素而不是索引的鍵。 當您沒有數據的唯一ID時,索引始終應該是第二選擇
更新:
您在減速器中遇到錯字錯誤,需要調用action.comment,但您正在調用action.comments。 檢查下面的更正
import {ADD_COMMENT} from './actions';
const initialState = {
comments: []
};
export default function(state = initialState, action){
if(action.type === ADD_COMMENT){
state.comments = action.comment;
return state;
}else{
return state;
}
}
更正的comments.js代碼
import React from 'react';
import {connect} from 'react-redux';
import CommentForm from './comment-form';
export function Comments(props) {
return (
<section>
<h2>Comments</h2>
<ul>
{Array.isArray(props.comments) && props.comments.length > 0 && props.comments.map((comment, index) => (
<li key={index}>
<div className="author">{comment.author} says: </div>
<div className="comment">{comment.comment}</div>
</li>
))}
</ul>
{!Array.isArray(props.comments) && <div>No comments</div>}
<h3>Add a comment</h3>
<CommentForm />
</section>
);
}
const mapStateToProps = (state, props) => {
return {"comments": state.comments}
};
export default connect(mapStateToProps)(Comments);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.