我想用react和redux实现下拉列表。下拉将是其他组件的一部分,因此,它真的是“哑”组件。但是下拉列表应该调用api来获取项目,应用自定义过滤器等。应该对Api调用进行身份验证,令牌存储为全局状态。我应该将令牌传递给组件道具吗?或者有更好的方法来做到这一点?
答案 0 :(得分:7)
根据定义,一个愚蠢的组件应该是愚蠢的:这意味着它应该从顶部",即通过道具,它应该采取它需要的一切。
只有" Smart" ("已连接"到Redux)组件,在层次结构中,将处理使用新的(异步)Action获取数据,然后在API调用返回时修改状态,这将重新呈现哑元组件及其新道具。
所以在Redux:
public void SaveData();
{
//need to get username from client
string user = GetUserName();
//save to database
}
您可能需要阅读此内容:http://redux.js.org/docs/basics/UsageWithReact.html
答案 1 :(得分:1)
Dumb组件并不意味着它可以执行任何类似获取更新的操作,这意味着它对redux的概念“愚蠢”,并且对您的商店或您正在使用的库一无所知。好处是你可以改变你的通量实现,你只需要做一些工作来更新智能组件。
对于您所描述的场景类型,您可以通过在<Menu>
想要更新数据时运行的道具为您的<Menu>
提供功能。 <Menu>
对Redux一无所知 - 它只是执行一个函数 - 但它仍然能够获取新数据。根据复杂性,您可以通过原始动作创建者(绑定到dispatchAction)并让它运行。
import * as dataActions from './actions';
// We have dataActions.fetchItems() which is the action creater to get new items.
// Attach items, and the action creator (bound to dispatch) to props
@connect((store) => {
return {items: store.data.items}
}, dataActions)
class ItemsPage extends Component {
static propTypes = {
items: PropTypes.object, // the items from the store, from @connect
fetchItems: PropTypes.func // action dispatcher, from @connect
}
render() {
return (<Menu onChange={this.props.fetchItems} /> )
}
}
// Our 'dumb' component that doesnt know anything about Redux,
// but is still able to update data (via its smart parent)
class Menu extends Component {
static propTypes = {
onChange: PropTypes.func // same as fetchItems
}
render() {
return (<button onClick={this.props.onChange}>Update items</button>);
}
}