我正在尝试将应用程序迁移到redux(newbie)。我有这段代码,我有点困惑设置初始状态的最佳实践。例如这是代码

class App extends Component {

 constructor(props) {
  super(props);
  this.state = {
      cityName: '',
      nameOfCity:'',
      weatherDescription:'',
      windSpeed:'',
      temperature:'',
      maxTemperature:'',
      minTemperature:''
  };
}

updateInfo(results){
  this.setState({
      nameOfCity: results.city.name,
      weatherDescription: results.list[0].weather[0].description,
      windSpeed: results.list[2].wind.speed,
      temperature: results.list[0].main.temp,
      maxTemperature: results.list[0].main.temp_max,
      minTemperature: results.list[0].main.temp_min
  });
   }

render() {
return (
  <div className="App">
    <div className="App-header">
      <img src={logo} className="App-logo" alt="logo" />
      <h2>Weather App</h2>
    </div>
    <p className="App-intro">
      To get started, edit <code>src/App.js</code> and save to reload.
    </p>
      <FormContainer label="Name of the city:" updateInfo={this.updateInfo.bind(this)}/>
      <WeatherInfo
          nameOfCity={this.state.nameOfCity}
          weatherDescription={this.state.weatherDescription}
          windSpeed={this.state.windSpeed}
          temperature={this.state.temperature}
          maxTemperature={this.state.maxTemperature}
          minTemperature={this.state.minTemperature}
      />
  </div>
  );
}
}


使用redux的最佳实践是什么

最佳答案

使用Redux时,您不需要以这种方式使用react状态。与所有应用程序数据一样。所有这些状态都应移至中央redux存储,并通过操作和化简器进行填充。然后,使用connectreact-redux方法将商店状态映射到组件的prop。

对于您的应用程序,updateInfo应该是操作的创建者,并具有简化程序,该操作可以将在此操作中发送的表单数据简化为状态。由于redux状态已映射到组件的props,因此视图将通过显示this.props.weatherDescription或所需的任何数据来按您期望的方式更新。

请查看文档here,以获取有关如何构建React Redux应用程序的完整信息。还有一个有关redux here入门的视频系列。

关于javascript - 如果我在React App中使用Redux设置初始状态,什么是最佳实践,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42365630/

10-12 00:07
查看更多