首页 文章

在状态改变后,react / redux组件不会重新渲染

提问于
浏览
0

我遇到了大麻烦,因为我确实需要快速学习反应/减少 . 我有2个组件,一个组成一个输出 . 表单勇敢地调度我的行为,我通过订阅我的控制台记录更改:everythings罚款正确,但以下组件不会重新呈现...任何想法?

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

const mapStateToProps = state => {
  return { message: state.message, speaker: state.speaker };
};

class connectedOutput extends Component {
    render(){
        const{message, speaker} = this.props
        return (<p>{speaker}: &nbsp;{message}</p>)
    }
}

const Output = connect(mapStateToProps)(connectedOutput);
export default Output;

这是我的减速机:

import { MESSAGE } from "../constants/action-types";
import { SPEAKER } from "../constants/action-types";
const initialState = {message:'Something', speaker:'Scotty'}

const basicReducer = (state = initialState, action) => {

    let speaker = state.speaker == 'Scotty' ? 'Bones' : 'Scotty';
    switch(action.type){
        case MESSAGE:
            Object.assign(state, action.message)
                return state;
            case SPEAKER:
                Object.assign(state, {speaker});
                return state;
            default:    
                return state;
        }
    };

    export default basicReducer;

初始状态正确呈现...这是我的包装提供商

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

2 回答

  • 2

    您没有从Object.assign返回新状态并始终返回旧状态 . 固定:

    switch(action.type){
        case MESSAGE:
            return Object.assign({}, state, { message: action.message })
        case SPEAKER:
            return Object.assign({}, state, { speaker });
        default:    
            return state;
    }
    
  • 0

    正确的减速机现在是:

    switch(action.type){
        case MESSAGE:
            return Object.assign({}, state, action.message )
        case SPEAKER:
            return Object.assign({}, state, { speaker });
        default:    
            return state;
    }
    

相关问题