Интерфейс не перерисовывается, хотя состояние магазина меняется? - PullRequest
0 голосов
/ 11 апреля 2019

У меня есть этот основной компонент, который подключен к хранилищу резервов методом подключения.

Я также использую промежуточное программное обеспечение регистратора для проверки состояния хранилища по мере его постепенного изменения, и оттуда я вижу, что хранилище успешно обновляется, но компонент, к которому он подключен, не выполняет рендеринг.

Пожалуйста, помогите ....

Я перепробовал почти все, включая использование Object.assign ({}), операцию распространения, а также попытался использовать componentWillReceiveProps (nextProps), но пользовательский интерфейс по-прежнему не обновляется.

Вот основной файл app.js:

import React from 'react'
import { render } from 'react-dom'
import App from './MainComponent'

import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import { Provider } from 'react-redux'
import thunk from 'redux-thunk'
import { reactReduxFirebase, getFirebase, firebaseReducer } from 'react-redux-firebase';
import firebase from './fbConfig'
import usersReducer from './reducers/usersReducer'
import logger from 'redux-logger'


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

const data = window.data;

delete window.data;

const store = createStore(usersReducer, data, applyMiddleware(logger(), thunk));

store.subscribe(() => {
    // console.log("Store State : " + JSON.stringify(store.getState()));
});

render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById("root")
)

где данные

{"users":[{"key":1,"value":{"employeeID":1,"firstName":"Siddharth Kilam","mobileNumber":"+919987792049","adminName":"Sid Kilam","adminID":36,"profileName":"default","profileID":4,"explicitLogin":1,"locRow":{"timestamp":"2019-04-09 09:15:05","lat":28.4453983,"lon":77.1012133,"eventTypeID":9,"employeeID":1},"attendanceRow":{"timestamp":"2019-04-09 09:05:39","lat":28.4453983,"lon":77.1012133,"eventTypeID":8,"employeeID":1},"workingStatus":{"code":0,"reason":"Normal Day","shifts":[{"startTime":"2019-04-11T04:34:00.000Z","endTime":"2019-04-11T12:34:00.000Z"}]},"offlinePeriod":3600000,"status":"Inactive"}},{"key":145,"value":{"employeeID":145,"firstName":"SidKilam2 Motorola","mobileNumber":"9599936991","adminName":"Sid Kilam","adminID":36,"profileName":"default","profileID":4,"explicitLogin":1,"locRow":{"timestamp":"2019-04-03 12:20:16","lat":28.4455203,"lon":77.101336,"eventTypeID":9,"employeeID":145},"attendanceRow":{"timestamp":"2019-04-02 23:01:27","lat":28.4747009,"lon":77.0989274,"eventTypeID":9,"employeeID":145},"workingStatus":{"code":0,"reason":"Normal Day","shifts":[{"startTime":"1999-12-31T18:30:00.000Z","endTime":"2000-01-01T18:29:59.000Z"}]},"offlinePeriod":3600000,"status":"Offline"}}]};

Файл редуктора

const GET_TASKS = 'get tasks'

export default (state = {}, action) => {
  switch (action.type) {
    case GET_TASKS:

      // return state.usersList.map(emp => {
      //   return Object.assign({}, emp.value, {
      //     firstName : "Neeraj Kumar Bansal"
      //   })
      // });

      return { ...state,  tasks : action.tasks }

    default:

      return state;
    }
 }

Файл действий

import database from '../fbConfig'

 /**
* ACTION TYPES
*/
const GET_TASKS = 'get tasks'

/**
* ACTION CREATORS
*/
export const getTasks = (tasks) => ({type: GET_TASKS, tasks})

/**
* THUNKS
*/
export function getTasksThunk() {
 return dispatch => {
 const tasks = [];
 database.ref(`/tasks/145/2019-01-14`).once('value', snap => {

  // console.log("Called ......................");

  snap.forEach(data => {
  let task = data.val();
  tasks.push(task)
  })

  // console.log("Tasks Fetched" + tasks);

 })
 .then(() => dispatch(getTasks(tasks)))
 }
}

Компонент пользовательского интерфейса IS:

import React, { Component } from 'react';
import { connect } from 'react-redux'
import { firebaseConnect } from 'react-redux-firebase'
import { compose } from 'redux'
import MapView from './components/map/MapView'
import MapComponents from './components/map/MapComponents';
import TasksSidebar from './components/map/TasksSidebar';
import { getTasksThunk } from './thunks/getTasksThunk'

class App extends Component {

  render() {

    // console.log("Props From Main Component : " + JSON.stringify(this.props.users));

    const { users } = this.props;
    // const { tasks } = this.state;

    console.log("Users From Main Component : " + users);
    // console.log("Tasks From Main Component : " + tasks);

    return (
      <div>
        <MapComponents users={users} />
        <TasksSidebar />
        <MapView users={users}/>
      </div>
    );
  }
}

// export default compose(
//   firebaseConnect((props) => {
//     return [
//       'Tasks'
//     ]
//   }),
//   connect(
//     (state) => ({
//       tasks: state.firebase.data.Tasks,
//       // profile: state.firebase.profile // load profile
//     })
//   )
// )(App)

const mapStateToProps = function(state) {
  console.log("Map State to props : " + state);
  return {
    users : state.users,
    tasks : state.tasks
  }
}

const mapDispatch = dispatch => {
  dispatch(getTasksThunk())
  return {

  }
 }

export default connect(mapStateToProps, mapDispatch)(App);

Интерфейс должен отображаться при изменении состояния хранилища ....

1 Ответ

0 голосов
/ 11 апреля 2019

Использовать статический компонент жизненного цикла getDerivedStateFromProps.Поскольку он выполняется для каждого повторного рендеринга.

Вы можете проверить условие там, если нет никаких изменений, просто вернуть ноль, иначе обновите состояние там.В состоянии getDerived из реквизита вы можете установить состояние, возвращая объект.функция setState здесь не будет работать, так как это статический метод.пожалуйста, обратитесь по этой ссылке https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops

// alter your store and reducer file
const store = createStore(usersReducer, applyMiddleware(logger(), thunk));

const GET_TASKS = 'get tasks';
const initialState = {
   users: [{"key":1,"value":{"employeeID":1,"firstName":"Siddharth Kilam","mobileNumber":"+919987792049","adminName":"Sid Kilam","adminID":36,"profileName":"default","profileID":4,"explicitLogin":1,"locRow":{"timestamp":"2019-04-09 09:15:05","lat":28.4453983,"lon":77.1012133,"eventTypeID":9,"employeeID":1},"attendanceRow":{"timestamp":"2019-04-09 09:05:39","lat":28.4453983,"lon":77.1012133,"eventTypeID":8,"employeeID":1},"workingStatus":{"code":0,"reason":"Normal Day","shifts":[{"startTime":"2019-04-11T04:34:00.000Z","endTime":"2019-04-11T12:34:00.000Z"}]},"offlinePeriod":3600000,"status":"Inactive"}},{"key":145,"value":{"employeeID":145,"firstName":"SidKilam2 Motorola","mobileNumber":"9599936991","adminName":"Sid Kilam","adminID":36,"profileName":"default","profileID":4,"explicitLogin":1,"locRow":{"timestamp":"2019-04-03 12:20:16","lat":28.4455203,"lon":77.101336,"eventTypeID":9,"employeeID":145},"attendanceRow":{"timestamp":"2019-04-02 23:01:27","lat":28.4747009,"lon":77.0989274,"eventTypeID":9,"employeeID":145},"workingStatus":{"code":0,"reason":"Normal Day","shifts":[{"startTime":"1999-12-31T18:30:00.000Z","endTime":"2000-01-01T18:29:59.000Z"}]},"offlinePeriod":3600000,"status":"Offline"}}],
   tasks: []
}

export default (state = initialState, action) => {
  switch (action.type) {
    case GET_TASKS:
      return { ...state,  tasks : action.tasks }

    default:
      return state;
  }
}

import React, { Component } from 'react';
import { connect } from 'react-redux'
import { firebaseConnect } from 'react-redux-firebase'
import { compose } from 'redux'
import MapView from './components/map/MapView'
import MapComponents from './components/map/MapComponents';
import TasksSidebar from './components/map/TasksSidebar';
import { getTasksThunk } from './thunks/getTasksThunk'

class App extends Component {

  constructor(){
    super();
    this.state = {
      users: []
    }
  }

  static getDerivedStateFromProps(props, state){

     if(props.users !== state.users){
        return {
           users: props.users    // This will update the props value for users in state
        }
     }

     return null;
  }

  render() {

    // console.log("Props From Main Component : " + JSON.stringify(this.props.users));

    const { users } = this.state;
    // const { tasks } = this.state;

    console.log("Users From Main Component : " + users);
    // console.log("Tasks From Main Component : " + tasks);

    return (
      <div>
        <MapComponents users={users} />
        <TasksSidebar />
        <MapView users={users}/>
      </div>
    );
  }
}

const mapStateToProps = function(state) {
  //console.log("Map State to props : " + state);
  return {
    users : state.users,
    tasks : state.tasks
  }
}

const mapDispatch = dispatch => {
  dispatch(getTasksThunk())
  return {

  }
 }

export default connect(mapStateToProps, mapDispatch)(App);
...