состояние отображается в реквизит только после рендеринга компонента - PullRequest
1 голос
/ 07 мая 2019

В настоящее время я создаю приложение с реакцией, редуксом и огнем. И я подключил Redux к FireBase и получаю данные из моей коллекции. Проблема заключается в том, что когда я пытаюсь отобразить избыточное состояние в свой компонент, он выполняет рендеринг компонента до отображения состояния, что выдает ошибку при попытке использовать .map ()

//Component I want to map the state to
import React, { Component } from "react";
import { Card, Button } from "reactstrap";
import { Link } from "react-router-dom";
import { connect } from "react-redux";
import { compose } from "redux";
import { firestoreConnect } from "react-redux-firebase";

export class Home extends Component {
componentDidUpdate() {
console.log(this.props.categories);
}
render() {
const { categories } = this.props;
return (
  <div className="container">
    <div className="row">
      {/* {this.props.categories.map((item, i) => (
        <div className="col-12 mt-3" key={i}>
          <Link to={`/category/${item}`}>
            <Card body inverse color="primary">
              <Button color="primary">{item}</Button>
            </Card>
          </Link>
        </div>
      ))} */}
      <div className="col-12 mt-3">
        <Link to="/new/category">
          <Card body inverse color="success">
            <Button color="success">Add Category</Button>
          </Card>
        </Link>
      </div>
      <div className="col-12 mt-3">
        <Link to="/new/item">
          <Card body inverse color="success">
            <Button color="success">Add Item</Button>
          </Card>
        </Link>
      </div>
      <div className="col-12 mt-3">
        <Link to="/history">
          <Card body inverse color="warning">
            <Button color="warning">History</Button>
          </Card>
        </Link>
      </div>
    </div>
  </div>
);
}
}

const mapStateToProps = state => {
// console.log(state);
return {
categories: state.firestore.ordered.categories
};
};

export default compose(
connect(mapStateToProps),
firestoreConnect([{ collection: "categories" }])
)(Home);

//Store.js file
import {
createStore,
compose,
combineReducers
} from "../../../../Library/Caches/typescript/3.2/node_modules/redux";
// import thunk from "redux-thunk";
// import rootReducer from "./components/reducers";
import firebase from "firebase";
import "firebase/firestore";
import { reactReduxFirebase, firebaseReducer } from "react-redux- 
firebase";
import { reduxFirestore, firestoreReducer } from "redux-firestore";

var firebaseConfig = {
apiKey: "xxxxx",
authDomain: "xxxxxx",
databaseURL: "xxxxxx",
projectId: "xxxxx",
storageBucket: "xxxxxx",
messagingSenderId: "xxxxx",
appId: "xxxxxx"
};

const rrfConfig = {
userProfile: "users",
useFirestoreForProfile: true
};

firebase.initializeApp(firebaseConfig);
// const firestore = firebase.firestore();

const createStoreWithFirebase = compose(
reactReduxFirebase(firebase, rrfConfig),
reduxFirestore(firebase)
)(createStore);

const rootReducer = combineReducers({
firebase: firebaseReducer,
firestore: firestoreReducer
});

const initialState = {};

// const middleware = [thunk];

const store = createStoreWithFirebase(
rootReducer,
initialState,
compose(
// applyMiddleware(...middleware),
reactReduxFirebase(firebase),
window.__REDUX_DEVTOOLS_EXTENSION__ && 
window.__REDUX_DEVTOOLS_EXTENSION__()
)
);

export default store;

Чтобы добавить немного больше информации, если я console.log (this.props.categories); используя componentDidMount () я получаю неопределенный. Но если я использую componentDidUpdate (), тогда я получу желаемый результат

Ответы [ 2 ]

0 голосов
/ 07 мая 2019

что-то вроде этого должно помочь:

class Yourcalss extends Component {


  constructor(props) {

  super(props);

  this.state = { yourstate: [] }
   }

 componentDidUpdate() {
 this.afterFetchProps();
 }

 afterFetchProps = () => {
 const yourState = this.props.map( 
 ///////////// your map )
 this.setState({ yourState });
 }

 render() {
 return(
 <div>{this.state.yourState}</div>
 )
 }

}

0 голосов
/ 07 мая 2019

У меня была такая же проблема, я думаю, что это проблема асинхронности, потому что ваш код будет выполнен, а состояние пусто попробуйте зарегистрировать ваши реквизиты в componentWillMount, чтобы убедиться, что реквизиты есть до рендера

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...