【发布时间】:2020-07-16 14:56:20
【问题描述】:
嘿,伙计们刚刚搬到 redux,所以我正在做的反应是在 componentDidMount() 中,我正在调用 api,一旦我收到数据,我就将加载设置为 false(最初加载为 true)以摆脱'反应微调',
但是现在在 componentDidMount() 中使用 redux 之后,我正在调用另一个位于另一个中的操作创建器,并且我正在接收我的数据,那么我如何在这里管理“加载”?我可以以某种方式将动作创建器中的某些内容传递给我的组件以触发状态并将加载设置为 false 吗?或者还有其他的吗?大家是怎么管理的?
这是我的代码
Home.js
class home extends Component {
UNSAFE_componentWillMount() {
this.props.verifyToken();
}
componentDidMount() {
this.props.categoryAction();
}
constructor(props) {
super(props);
this.state = {
categoriesWithTheirImages: [],
displayToggle: false,
loading: false,
};
}
renderCategory = () => {
return this.props.allCategories.map((item) => {
return (
<div
className="category_div"
key={item._id}
onClick={() => this.setState({ displayToggle: true })}
>
<img
src={item.image}
alt="miss-mistake"
className="category_image_home"
/>
<span className="category_heading_home">{item.categoryName}</span>
</div>
);
});
};
render() {
if (this.state.loading) {
return (
<div className="sweet-loading-main">
<FadeLoader
css={override}
sizeUnit={"px"}
size={50}
color={"#ff9d72"}
loading={this.state.loading}
/>
</div>
);
} else {
console.log(this.props.allCategories);
return (
<React.Fragment>
{/* <Fade left> */}
<Header />
<div className="main_content_homepage">
<p className="category_select">Please select a category</p>
<div className="category_list">{this.renderCategory()}</div>
</div>
{this.renderStoryActionDialog()}
{/* </Fade> */}
</React.Fragment>
);
}
}
}
const mapStateToProps = (state) => {
console.log(state);
const images = [family, ring, beer, feedback, academic];
let categoriesWithImages = state.getCategoryReducer.map((item, index) => {
item.image = images[index];
return item;
});
console.log(categoriesWithImages);
return { allCategories: categoriesWithImages };
};
export default connect(mapStateToProps, { verifyToken, categoryAction })(home);
还有我的 action.js 文件
import { CATEGORY } from "../actionTypes";
export const categoryAction = ()=> {
return dispatch => {
fetch("http://localhost:3000/api/get_categories", {
method: "GET",
}).then(res=>res.json())
.then(response => {
console.log(response)
dispatch({ type: CATEGORY, payload: response });
})
.catch(err => console.log("Eror in adding", err));
};
};
reducer 文件
import { USER, CATEGORY} from "../actionTypes";
const getCategoryReducer = (state = [], action) => {
switch (action.type) {
case CATEGORY:
return action.payload;
default:
return state;
}
};
export default getCategoryReducer;
【问题讨论】:
-
我通常也会在我的 redux 存储中保持加载状态,所以当你完成加载时,你可以发送一个
LOADED动作。另一种选择是在组件中添加loaded,这取决于allCategories属性中是否包含任何内容。
标签: javascript reactjs redux react-redux redux-thunk