在 Redux 中使用 Action 的正确方法

Proper way to use Action in Redux

我正在做一个猜色游戏。我有一个名为 generateColors() 的动作,它生成 9 种颜色,并且将从这 9 种颜色中随机选择一个答案。我的 App.js 呈现 Header.jsBoxGrid.js.

目前我在 BoxGrid.js 中调用 generateColors()。将答案传递给 Header.js 的正确方法是什么?我应该在 App.js 中调用 generateColors() 吗?

BoxGrid.js

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

import Box from '../components/box';
import { generateColors } from '../actions';

class BoxGrid extends Component{

    componentDidMount(){
        this.props.generateColors();
    }

    render(){
        return(
            <div>
                <div className="grid">
                    {this.props.colors.map((color)=>{
                        return <Box key={color} color={color}/>
                    })}
                </div>
            </div>
        )
    }
}

function mapState({colors}){
    return {colors};
}

export default connect(mapState,{generateColors})(BoxGrid);

提前致谢。

我不确定应用程序的外观,所以我可能是错的。

因为您使用的是 Redux,只需将答案保存到您的 Redux 商店,然后将 Header 连接到商店(或者只需连接 App 并将道具向下传递到 Header, 都很好)

在这种情况下,我个人更愿意将该操作放在 App.js 中,因此 BoxGrid 不需要关心任何应用程序逻辑,只需呈现 UI .不过我觉得这只是个人口味,没有正确答案。

你可以在这里查看 Redux 文档的常见问题:

Should I only connect my top component, or can I connect multiple components in my tree?

http://redux.js.org/docs/faq/ReactRedux.html#should-i-only-connect-my-top-component-or-can-i-connect-multiple-components-in-my-tree

我假设 answer 你的意思是用户正在选择一种颜色,并且你想将该用户输入从一个组件传递到另一个组件。有几种方法可以做到这一点。您可以将 App 中的一个函数作为 prop 传递给下面的组件,当该函数被调用时,它会在 App 中设置本地状态,该状态也会传递给 child 组件:

class App extends Component {
  constructor(props) {
     super(props)
     this.state = {
        answer: null
     }
  }

  updateAnswer(answer) {
     this.setState({ answer: answer })
  }

  render () {
     return <div>
        <Header answer={this.state.answer} />
        <BoxGrid answer={this.state.answer} updateAnswer={this.updateAnswer.bind(this)} />
     </div>
  }
}

然后,当 BoxGrid 调用 this.props.updateAnswer(answer) 时,它将传递给 header。这不使用 Redux 商店。

另一种方式是使用Redux store,调用action。如果您在多个组件之间共享数据,这可能比使用上述本地状态更有意义。与您已经发布的非常相似,您可以连接任何组件并获取全局状态。不用在 App 组件中设置本地状态,你会有一个 answer reducer,它看起来像:

function answer (state = { answer: null }, action) {
  if (action.type === 'saveAnswer') {
    return { answer: action.answer }
  }
}

还有一个 saveAnswer 动作创建者,例如:

function saveAnswer (answer) {
  return {
     type: 'saveAnswer',
     answer: answer
  }
}

然后,如果您将 App 组件与 mapStateToProps 连接起来,您只需从商店中获取答案,然后 return 它作为道具,可以传递给任何人child 组件。随着您的层次结构变得越来越复杂,您可以选择连接任何 child 组件,但如果您总共只有 3 个组件,则仅连接 App 并从商店传递数据可能更有意义道具.