即使商店状态发生了变化,UI是否也没有重新显示?

时间:2019-04-11 06:34:57

标签: reactjs redux redux-thunk

我有这个主要组件,它通过connect方法连接到redux存储。

我还使用记录器中间件来检查存储状态,因为存储状态会逐渐变化,从那里我可以看到存储已成功更新,但是所连接的组件未重新呈现。

请帮助。...

我已经尝试了几乎所有方法,包括使用Object.assign({}),传播操作,还尝试使用componentWillReceiveProps(nextProps),但ui仍未更新。

这是主要的app.js文件:

ball.x += ball.speed * Math.sin(ball.angle)
ball.y += ball.speed * -Math.cos(ball.angle)

数据在哪里

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")
)

Reducer文件是

{"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;
    }
 }

UI组件IS:

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)))
 }
}

随着商店状态的改变,UI应该重新呈现。...

1 个答案:

答案 0 :(得分:0)

使用静态getDerivedStateFromProps生命周期组件。在每次重新渲染时执行。

您可以检查那里的条件,如果没有更改,则返回null,否则更新那里的状态。在props的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);