问题描述
enter image description here 此处的 singleCard 对象包含有关产品的所有详细信息,例如 id、title、src 等。我可以将 singleCard 控制台记录为 console.log(singleCard),其中显示从 redux store 传递的所有数据,但我无法访问其单个元素,如 singleCard.src 或 singleCard.title 。我想在 useState 钩子的帮助下通过将 initialState 设置为 singleCard.src 来展示图像,我该怎么做??
function Singlecard() {
const dispatch = useDispatch();
const { id } = useParams();
const productId = id;
const productDetails = useSelector((state) => state.productDetails);
const { loading,error,singleCard } = productDetails;
const [currentImg,setcurrentimg] = useState(singleCard.src);
console.log(currentImg);
useEffect(() => {
dispatch(detailsProduct(productId));
},[dispatch,productId]);
return (
<div>
<div className="singlecard-wrapper">
<div className="singlecard">
{/* card left */}
<div className="product-img">
<div className="img-display">
<div className="img-showcase">
<img src={currentImg} height="552px" width="552px" />
</div>
</div>
<div className="img-select">
<div className="img-item">
<Link to="#">
<img
src="https://instagram.fccu3-1.fna.fbcdn.net/v/t51.2885-15/e35/121105212_197680348436281_873870113726337107_n.jpg?tp=1&_nc_ht=instagram.fccu3-1.fna.fbcdn.net&_nc_cat=101&_nc_ohc=nsNxf_rVgeUAX9KUkp-&edm=AP_V10EAAAAA&ccb=7-4&oh=6b955579988a6dcbef129b3ad606fecd&oe=60918B32&_nc_sid=4f375e"
onClick={(e) => setcurrentimg(e.target.src)}
/>
</Link>
</div>
</div>
</div>
</div>
</div>
在 useState 中使用 singleCard.src 时,它显示无法读取 undefined 的属性“src”。请帮忙!
productAction:
export const detailsProduct = (productId) => async (dispatch) => {
dispatch({ type: PRODUCT_DETAILS_REQUEST,payload: productId });
try {
const response = await axios.get(`/cardUpload/${productId}`);
dispatch({ type: PRODUCT_DETAILS_SUCCESS,payload: response.data });
} catch (err) {
dispatch({
type: PRODUCT_DETAILS_FAIL,payload:
err.response && err.response.data.message
? err.response.data.message
: err.message,});
}
};
productReducer:
export const detailsProduct = (productId) => async (dispatch) => {
dispatch({ type: PRODUCT_DETAILS_REQUEST,});
}
};
商店:
import { applyMiddleware,combineReducers,compose,createStore } from "redux";
import thunk from "redux-thunk";
import {
productDetailsReducer,productListReducer,} from "./reducers/productReducers";
const initialState = {};
const reducer = combineReducers({
productList: productListReducer,productDetails: productDetailsReducer,});
const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
reducer,initialState,composeEnhancer(applyMiddleware(thunk))
);
export default store;
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)