为什么在react / redux

时间:2016-07-27 04:07:23

标签: reactjs redux

我的React / Redux应用程序出现问题。我试图通过在componentDidMount中调度一个动作来检查一个人是否已登录。我在我的应用程序中登录控制台以查看控制流,它通过response.ok进入reducer,我记录了操作和状态。然后我的reducer返回一个新状态。但是,视图未正确更新,因为在我看来,state.signedIn属性未正确更新显示按钮而不是指示用户已登录的文本。

这是我的组成部分:

class Attendance extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      email: props.user.email,
      name: props.user.name,
      id: props.user.id
    };
  }

  componentDidMount() {
    this.props.dispatch(checkSignIn(this.state.id));
  }


  render() {

    const page = this.state.signedIn ? (
        <div>
          Congratulations you have signed
        </div>
      ) : (
      <div>
        <button>Attendance</button>
      </div>
    );
    return page;
  }
}

const mapStateToProps = (state) => {
  return {
    token: state.auth.token,
    user: state.auth.user,
    signedIn: state.signedIn
  };
};

export default connect(mapStateToProps)(Attendance);

这是我的行动:

export function checkSignIn(id) {
  return (dispatch) => {
    dispatch({
      type: 'CLEAR_MESSAGES'
    });
    return fetch('/checkAttendance', {
      method: "post",
      headers: {"Content-type":"application/json"},
      body: JSON.stringify({
        id: id
      })
    }).then((response) => {
      if (response.ok) {
        console.log("response === ", response);
        return response.json().then((json) => {
          console.log("json === ", json);
          dispatch({
            type: "CHECK_ATTENDANCE_SUCCESS",
            message: json
          });
        });
      }else{
        console.log("response not okay");
        return response.json().then((json) => {
          dispatch({
            type: "CHECK_ATTENDANCE_FAILURE",
            message: json
          });
        });
      }
    })
  }

这是我的减速机:

const initialState = {
    signedIn: false,
}

export default function attendance(state = initialState, action){
    if (!state.hydrated) {
        state = Object.assign({}, initialState, state, { hydrated: true});
    }
  switch (action.type) {
    case "CHECK_ATTENDANCE_SUCCESS":
      console.log("check attendance success");
      console.log("state === ",state);
      console.log("action === ", action);
      return Object.assign({}, state, {
        signedIn: action.message.signedIn
      });
    default:
      return state;
  }
}

0 个答案:

没有答案