React Redux:获取props和更新状态

IT技术 javascript reactjs redux
2021-05-15 02:24:57

我是第一次尝试 React/Redux/JS。我对在组件中设置状态与让 redux 更新它有点困惑。

我想单击一个按钮将 lightOn 设置为 true 并显示更新的 this.props.lightOn 值。我错过了一些基本的东西,但不确定是什么。

行动:

export const setLight = lightStatus => dispatch => {
  const res = lightStatus;
  console.log(res); // => true on click

  dispatch({ type: SET_LIGHT, payload: res });
};

在组件中, {this.props.onLight} 未定义,所以我没有正确更新状态:

import React, { Component } from 'react';
import { connect } from 'react-redux';
//import * as actions from '../actions';
import { setLight } from '../actions';
import { bindActionCreators } from 'redux';

class Light extends Component {
  render() {

    return (
      <div>
        Light Status: {this.props.lightOn}
        <button
          className="btn"
          onClick={() => this.props.setLight(true)}
        >
          Set Light!
        </button>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    lightOn: state.lightOn
  };
}

function mapDispatchToProps(dispatch) {
  //whenever selectBook is called the result should be passed to all of our reducers
  return bindActionCreators({ setLight: setLight }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(Light);

减速器(使用扩展运算符更新):

import { SET_LIGHT } from '../actions/types';

export default function(state = [], action) {
  switch (action.type) {
    case SET_LIGHT:
     return { ...state, lightOn: action.payload };
    default:
      return state;
  }
}
4个回答

如何将其设置为状态而不是直接传递给函数?首先将其绑定到 Constructor 中,然后单击 setState 为 true ?

constructor(props) {
super(props);
this.state:{lightOn: false};
this.OnClick = this.OnClick.bind(this);
}

onClick(event) {
this.setState({lightOn: true});
}

onClick ={this.onClick()}

当您使用 redux 时,您可以通过返回一个新状态来代替

   return {...state, action.payload };

怎么运行的?通过connect你可以注入用于控制 redux 状态的 props 并将其绑定到组件。例如:

class SomeComponent extends React.Component {
    componentWillMount() {
        this.props.sendSomething('someName');
    }

    render() {
        return (
            <div>{this.props.stateProp}</div>
        )
    }
}

const mapStateToProps = state = ({
    stateProp: state.someReduxState,
});

const mapDispatchToProps = dispatch => ({
    sendSomething: (name) => dispatch(someActionCreator(name)),
});

const ConnectedComponent = connect(
    mapStateToProps,
    mapDispatchToProps,
)(SomeComponent);

在给定的示例中,您将someReduxStatestate 的一部分绑定stateProp,它被注入到组件中。您正在注入sendSomething将在 redux 中调度和操作的方法 ( )。如果组件中继显示部分 redux 状态,则每次 redux 状态更改时都会更新它,因为注入到组件中的 props 会更改。您可以在此处的官方 Redux 文档中找到更多信息,也可以在此处观看有关 egghead 的免费教程

你不是在这里返回一个新的状态

export default function(state = [], action) {
  switch (action.type) {
    case SET_LIGHT:
      return action.payload;
    default:
      return state;
  }
}

你直接返回action.payload,这很简单lightStatus

你可以这意味着无法访问state.lightOn您的mapStateToProps

你应该做的

 case SET_LIGHT:
              return {
                ...state,
                lightOn: action.payload,
              };

或者直接

case SET_LIGHT:
                  return {
                    ...state,
                    action.payload,
                  };

这样整个状态就不会丢失,也不会直接改变状态。在这里,为了简单起见,我使用对象扩展运算符而不是Object.assign

减速器上的错误,减速器应该使用 lightOn 键返回状态对象,但是您返回有效载荷值,这就是问题所在。你的减速器应该像这样返回带有有效载荷值的 lightOn。

import { SET_LIGHT } from '../actions/types';

export default function(state = {}, action) {
  switch (action.type) {
    case SET_LIGHT:
      return {...state, action.payload}
    default:
      return state;
  }
}