我正在创建一个饮料计数器,该计数器将计算学习Redux的项目中消耗的饮料量。
我有一个初始状态,具有一个酒水属性,其中包含酒水的集合及其当前计数:
//State
{
drinks: {
coffee: 0,
water: 0,
}
//...
}
我创建了一个Counter
演示文稿组件:
import React from 'react';
import PropTypes from 'prop-types';
import Button from './Button';
const ucFirst = string => string.charAt(0).toUpperCase() + string.slice(1);
const Counter = ({name, count, onIncrement, onDecrement}) => (
<div className="counter">
<h2>{ucFirst(name)}</h2>
<span>{count}</span>
<Button onClick={() => {onIncrement(name)}}>+</Button>
<Button onClick={() => {onDecrement(name)}}>-</Button>
</div>
);
Counter.propTypes = {
name: PropTypes.string.isRequired,
count: PropTypes.number.isRequired,
onIncrement: PropTypes.func.isRequired,
onDecrement: PropTypes.func.isRequired,
}
export default Counter;
后跟DrinkCounter
容器组件:
import { connect } from 'react-redux'
import { incrementDrink, decrementDrink } from '../actions'
import Counter from '../components/Counter'
const mapStateToProps = (state, ownProps) => ({
count: state.drinks[ownProps.drink],
name: ownProps.drink
})
const mapDispatchToProps = dispatch => ({
onIncrement: drink => dispatch(incrementDrink(drink)),
onDecrement: drink => dispatch(decrementDrink(drink))
})
export default connect(
mapStateToProps,
mapDispatchToProps
)(Counter)
如果我添加
,这将按预期工作<DrinksContainer name="coffee" />
进入我的App
组件。
现在这是问题开始的地方,我想再创建两个组件,一个是表示性的,另一个是将在我的drinks
对象的键上映射的容器,并为每个对象输出一个DrinkCounter
以下代码,但出现错误“道具类型失败:道具name
在Counter
中标记为必需,但其值为undefined
”
这是List
容器:
import React, {Fragment} from 'react'
import PropTypes from 'prop-types'
import DrinkCounter from '../containers/DrinkCounter'
const List = ({drinks}) => {
return (
<Fragment>
{
Object.keys(drinks).map(
(drink, index) => (<DrinkCounter name={drink} key={index} />)
)
}
</Fragment>
)
}
List.propTypes = {
drinks: PropTypes.object.isRequired
}
export default List
这是DrinksList
容器:
import React from 'react';
import {connect} from 'react-redux';
import List from '../components/List';
const mapStateToProps = state => ({
drinks: state.drinks
})
export default connect(mapStateToProps)(List);
有人可以解释我要去哪里错吗?
答案 0 :(得分:0)
我已经解决了这个问题,在List
组件中,我为DrinkCounter
提供了错误的支持,而实际上我应该通过name
来传递drink
。