当我试图用一个提取的json调度一个操作时,我在这里缺少了什么



我想在表单提交时更新redux状态。但在这里,我的操作失败了,或者发生了其他smth,所以我得到了错误,组件没有渲染。我不知道useEffect在这里是否有帮助,但我仍然没有找到错误发生的原因。我应该使用redux形式还是类似的smth形式?

我得到的错误:reduPhotos.map不是一个函数

ReduxPhotos是initialState的一个照片数组。

const reduxPhotos = useSelector(state => state.photos)

这里有一个完整的代码:

// action
export const addPhotos = (photos) => {
return {
type: 'ADD_PHOTOS',
photos
}
}
// reducer
const initialState = {
photos: [],
collections: [],
favorites: []
}
function rootReducer (state = initialState, action) {
switch (action.type) {
case 'ADD_PHOTOS':
return { ...state, photos: action.photos }
case 'ADD_COLLECTIONS':
return { ...state, collections: action.collections }
case 'ADD_TO_FAVORITES':
return { ...state, favorites: [...state.favorites, action.photo] }
// case 'REMOVE_FROM_FAVORITES':
//   return { ...state, collections: action.collections }
default:
return state
}
}
// and here is my Search component
const Search = ({ unsplash }) => {

const reduxPhotos = useSelector(state => state.photos)
const dispatch = useDispatch()
const [value, setValue] = useState('')
const handleChange = (e) => {
setValue(e.target.value)
}
const handleSubmit = (e) => {
e.preventDefault()
unsplash.search.photos(value, 1, 10, { orientation: 'portrait', color: 'green' })
.then(toJson)
.then(json => {
console.log(json) // it logs correctly
dispatch(addPhotos(json)) // this thing does not work
})
}
return (
<div className='search'>
...
<form onSubmit={handleSubmit}>
<input className='panel__input' placeholder='Search' onChange={handleChange}/>
</form>
<ul className="search__list">
{reduxPhotos.map((item) => {
return (
<li key={item.id} className="search__photo photo">
...
</li>
)
})}
</ul>
...
</div>
)

你好,试试这个:

switch (action.type) {
case 'ADD_PHOTOS':
return [ ...state, {photos: action.photos}]
default:
return state
}

switch (action.type) {
case 'ADD_PHOTOS':
return [ ...state, {action.photos}]
default:
return state
}

相关内容

最新更新