我有點卡住,我想寫的東西博客類型,使用戶通過帖子中導航。我爲此使用了反應路由器,以便每當用戶導航到/posts/:id
時,都會顯示相關帖子。防止反應路由器試圖訪問非現有對象(在REDX中)? (簡單的博客網站)
到目前爲止,我有這樣的:
import React from 'react'
import {connect} from 'react-redux'
import {fetchPost} from '../actions/posts.actions.js'
class PostView extends React.Component {
constructor(props) {
super(props);
this.setNextPost = this.setNextPost.bind(this);
this.setPreviousPost = this.setPreviousPost.bind(this);
}
setPreviousPost() {
var {id} = this.props.match.params;
if(id>1) {
id--;
}
this.props.history.push('/posts/'+id);
}
setNextPost() {
var {id} = this.props.match.params;
id++; //i need to have something (maybe here? or elsewhere in this file?) that does not let the id go too high
this.props.history.push('/posts/'+id);
}
render() {
// var {id} = this.props.match.params;
return (
<div>
<h1>{this.props.activePost.post}</h1>
{/* <h1>{this.props.posts[id].post}</h1> */}
<button onClick={this.setPreviousPost}>Previous</button>
<button onClick={this.setNextPost}>Next</button>
</div>
);
}
}
function mapStateToProps ({posts}, ownProps) {
return {
activePost: posts[ownProps.match.params.id]
};
}
export default connect(mapStateToProps, {fetchPost})(PostView);
說我有總共10個職位。與上面的代碼,如果用戶導航到posts/11
,我得到一個錯誤(因爲職位根本不存在,因此未定義):
index_bundle.js:53908 Uncaught TypeError: Cannot read property 'post' of undefined
at PostView.render (index_bundle.js:53908)
at index_bundle.js:37770
at measureLifeCyclePerf (index_bundle.js:37050)
所以我需要以某種方式阻止用戶從導航到一個職位,這是不存在的。我不知道該怎麼做。
一些更多的背景:起初,我創建了一個CurrentPost減速,它總是保持目前的職位代碼,直到有人在一些教程中指出,這倒是應該不會被保存在一個單獨的減速,因爲reactrouter已經持有posts/:id
的post id
然後可以用於從我posts reducer
獲取職位。這對我來說聽起來很不錯,然而我改變了一切,但是,現在我不知道在哪裏以及如何驗證我的數據是正確的,我不確定在組件本身中完成所有這些是否是一個好主意。
編輯:
我有一個帖子減速持有的所有職位。它是一個很大的JavaScript對象,看起來像這樣:
{
"1" : {post: "post no 1", title: "Hello", ...},
"2" : {post: "post content no. 2", title: "...", },
//...
}.
我目前沒有保留減速器中的帖子數量。我也沒有(現在)將大帖子縮減器傳遞給我的單個帖子視圖組件(我上面引用的那個組件),並且現在只需在相關標識中獲取帖子。
您是否有權訪問該組件中帖子的ID列表? I.E是它還是可以作爲道具傳遞? – spirift
嗯。我有一個'職位減速器',其中包含所有職位。它是一個很大的javascript對象,看起來像這樣:'{「1」:{// ...第一個發佈對象},「2」:{//第二個發佈對象},// ...}'。所以我目前沒有保留減速器中的帖子數量。我也沒有(現在)將大帖子縮減器傳遞給我的單個帖子視圖組件(我上面引用的那個組件),並且現在只需在相關標識中獲取帖子。 –