簡體   English   中英

React Redux不同步mapStateToProps中的道具

[英]React redux do not sync props in mapStateToProps

我正在將React redux與Firebase實時數據庫一起使用。 在App.js中,我調度了一個動作fetchAllPosts

App.js

class App extends Component {
  componentDidMount() {
    this.props.fetchAllPosts();
  }
  render() {
    return (
      <div className="App">
          // something ...
      </div>
    );
  }
}
const mapDispatchToProps = dispatch => {
  return {
      fetchAllPosts: () => {dispatch(allPosts())}
  }
}

我的動作如下所示(我正在使用redux-thunk):

行動

export function allPosts() {
    return (dispatch) => {  
firebase.database().ref('posts/').on('value', (snapshot) => {
        dispatch({type: "ALL_POSTS", postsArray: snapshot.val(), loading: false})
    })
    }
}

然后,我正在組合減速器(我知道在這種情況下沒有必要):

const rootReducer = combineReducers({
    allPosts: postsReducer
})

我的減速器看起來像這樣:

減速器

const initialState = {
    allPosts: []
}

const postsReducer = (state = initialState, action) => {
    switch(action.type) {
        case "ALL_POSTS" :
        console.log("action payload all posts", action.postsArray)
        return {
            ...state,
            loading: false,
            allPosts: action.postsArray
        }
        break;
        default:
        return state
    }
    return state
}

最后:我的SinglePostview組件如下所示: SinglePostview.js

import React, {Component} from 'react';
import {connect} from 'react-redux';

class SinglePostview extends Component {
    render() {
        console.log("ppp", this.props)
        return (
            <h2>{this.props.post.title}</h2>
        )
    }
}

const mapStateToProps = (state, ownprops) => {
    const postId = ownprops.match.params.postid
    return {
        post: state.allPosts.allPosts[postId]
    }
}

export default connect(mapStateToProps)(SinglePostview);

在這里,當執行render方法時, this.props.post是未定義的,並且出現錯誤:

TypeError:無法讀取未定義的屬性“ title”。

問題是:當應用程序首次加載時, props.post是未定義的(所以我有一個錯誤),大約1秒鍾后,它接收到該值,但它沒有任何改變-錯誤仍然存​​在,並且值是不顯示。 有人可以幫我嗎?

假設您的減速器很好,您可以通過以下方法解決此問題

改變這個

render() {
        return (
            <h2>{this.props.post.title}</h2>
        )
    }

對此:

render() {
        if (!this.props.post){
            return null;
        }
        return (
            <h2>{this.props.post.title}</h2>
        )
    }

要么

render() {
        return (
            <h2>{this.props.post && this.props.post.title}</h2>
        )
    }

您正在將allPost定義為數組

    const initialState = {
    allPosts: []
    }

但是您試圖像訪問對象一樣訪問它。

state.allPosts.allPosts[postId]

因此,如果您的state.allPosts.allPosts是一個數組,請嘗試使用ES6 find()方法從具有postId的數組中獲取帖子。

假設

state.allPosts.allPosts = [
   {postId: 1,title:'abcd'},
   {postId:2,title:'def'}
]
 state.allPosts.allPosts.find(post => postId === post.postId)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM