Skip to content

react-redux在react和redux中的应用及理解 #43

Description

@incuisting

react-redux提供了两个东西

  • provide
  • connect

provide为组件提供一个共同的context,而connect则提供一个手段可以把store与容器组件连接起来,让容器组件可以拿到store里面的state,和用dispatch来调用action。
主要通过以下形式

const mapStateTopProps = (state) => { //从store里面拿出数据当作props传给需要连接的容器组件
  const weatherData = state.weather;

  return {
    status: weatherData.status,
    cityName: weatherData.city,
    weather: weatherData.weather,
    lowestTemp: weatherData.temp1,
    highestTemp: weatherData.temp2
  };
}


const mapDispatchToProps = (dispatch) => { //触发action 的方法
  return {
    onSelectCity: (cityCode) => { //这个方法也是通过props的形式传给被连接的容器组件
      dispatch(weatherActions.fetchWeather(cityCode));
    }
  }
};
export default  connect(mapStateTopProps,maDispatchToProps)(Weather);//最后一个括号里面的是当前需要被连接的容器组件

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions