React / Redux - 组件状态不更新

时间:2018-02-05 12:15:29

标签: javascript reactjs redux reducers

似乎我在React / Redux中遇到了一个非常常见的问题。有很多人都有这个问题,但原因可能会有很大不同,所以我找不到可能的解决方案。 我正在尝试构建一个带有列表的网页,可以通过按向上和向下按钮重新排序。

我已设法跟踪更新的状态(数组),直到reducer但组件未更新。我相信我没有正确更新组件的状态。

这是我的组件:

import React, { Component } from 'react';
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { changeOrder } from "../actions/index.js";

// let list = ["apple", "banana", "orange", "mango", "passion fruit"];

export class Home extends Component {
  constructor(props){
    super(props);
    this.renderList = this.renderList.bind(this);
  }

  goUp(position){
    this.props.changeOrder(position, "up");
  }

  goDown(position){
    this.props.changeOrder(position, "down");
  }

  renderList(fruit){
    const position = this.props.list.indexOf(fruit);
    return (
          <div key={fruit}>
            <li>{fruit}</li>
            <button onClick={() => this.goUp(position)}>Up</button>
            <button onClick={() => this.goDown(position)}>Down</button>
          </div>
        );
  }

  render() {
      return (
        <div>
          <h1>This is the home component</h1>
          <ol>
            {this.props.list.map(this.renderList)}
          </ol>
        </div>
      );
  }
}

function mapStateToProps(state){
  console.log(state);
    return { list: state.list };
}

function mapDispachToProps(dispatch) {
    return bindActionCreators({ changeOrder }, dispatch);
}

export default connect(mapStateToProps, mapDispachToProps)(Home);

动作:

export const GO_UP = "GO_UP";
export const GO_DOWN = "GO_DOWN";

export function changeOrder(position, direction) {
    console.log("position: " + position + " | direction: " + direction);
   switch (direction) {
       case "up": {
           return {
                type: GO_UP,
                payload: position
           };
       }
       case "down": {
           return {
               type: GO_DOWN,
               payload: position
           };
       }
   }
}

减速机:

import { GO_UP, GO_DOWN } from "../actions/index.js";
let list = ["apple", "banana", "orange", "mango", "passion fruit"];

function arrayMove(arr, old_index, new_index) {
    if (new_index >= arr.length) {
        var k = new_index - arr.length + 1;
        while (k--) {
            arr.push(undefined);
        }
    }
    arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
    return arr; // for testing
}

export default function (state = list, action){
    // debugger;
    switch (action.type){
        case GO_UP: {
            let newState = arrayMove(state, action.payload, action.payload -1);
            console.log(newState);
            return newState;
        }
        case GO_DOWN: {
            let newState = arrayMove(state, action.payload, action.payload +1);
            console.log(newState);
            return newState;
        }
        default: return list;
    }
}

这是reducer的Index.js:

import { combineReducers } from 'redux';
import ReducerList from "./reducer_list";

const rootReducer = combineReducers({
  list: ReducerList
});

console.log(rootReducer);

export default rootReducer;

最后是index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import ReduxPromise from "redux-promise";

import App from './components/app';
import reducers from './reducers';

const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <App />
  </Provider>
  , document.querySelector('.container'));

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

问题位于函数arrayMove()中的reducer中。您正在更改名为arr的现有数组。在更改它之后,React组件不知道属性state.list实际上已更改,因为内存引用遵循相同的旧数组(具有更改的内容)。

要告诉您的应用程序,该列表实际已更改,您需要返回NEW数组。就像arrayMove中的所有逻辑一样,最后你需要返回类似的东西:

return [].concat(arr);

在函数式编程术语中,arrayMove是一个带有副作用的脏函数,因为它通过它的引用来改变现有的对象/数组。 “clean”函数应该返回一个对象的新实例。

答案 1 :(得分:1)

当您使用react-redux时,您希望确保不改变状态,而是需要创建一个新的状态对象(浅层副本)。有关详细信息,请参阅here。如果改变先前的状态,Redux将不知道状态是否已更新。

在arrayMove中

你正在改变当前状态。而不是

arrayMove(state, action.payload, action.payload -1);

使用以下内容,

arrayMove(state.slice(), action.payload, action.payload -1);
相关问题