你们如何在redux减速机中处理装载状态的初始状态?这总是如此吗?问题是你必须在以后的reducer中将它设置为false。
喜欢这样
const initState = {
loading: true,
data: null,
error: null
}
export function global(state=initState, action) {
switch(action.type){
case FETCHING:
return {
...state,
loading: true
}
case FETCH_SUCESS:
return {
...state,
data: action.payload,
loading: false
}
case FETCH_FAILED:
return {
...state,
error: action.payload.error,
loading: false
}
default:
return state
}
}
如果设置为false,则会出现此问题
class AClassName extends Component {
constructor(props){
super(props)
props.callAnApi()
}
//assume in reducer your loading initialstate is false
render() {
this.props.something && return <Redirect to={`/app/${this.props.something}`} />
return !this.props.loading && <SomethingElse { ...this.props } />
}
}
如果已完成加载,如何不返回任何内容。上面的问题是SomethingElse组件仍然会被渲染一次,这不是我想要的。那么你的初始加载状态是什么?
答案 0 :(得分:1)
const initState = {
loading: false,
data: null,
error: null
}
export function global(state=initState, action) {
switch(action.type){
// Called first thing as part of callAnApi
case FETCHING:
return {
...state,
loading: true
}
case FETCH_SUCESS:
return {
...state,
data: action.payload,
loading: false
}
case FETCH_FAILED:
return {
...state,
error: action.payload.error,
loading: false
}
default:
return state
}
}
class AClassName extends Component {
constructor(props){
super(props);
}
componentWillMount() {
this.props.callAnApi();
}
//assume in reducer your loading initialstate is false
render() {
this.props.loading && return <SomethingElse { ...this.props } />
this.props.something && return <Redirect to={`/app/${this.props.something}`} />
}
}
此流程一直对我有用
答案 1 :(得分:-1)
考虑条件渲染,
用于渲染,this.props.loading
应该是假的
并跳过渲染,
this.props.loading
应该是真的。
你可以简单地合并
默认initState
默认值e.g.loading = true
。
const initState = {
loading: true,
data: null,
error: null
}
export function global(state = initState, action) {
switch (action.type) {
case FETCHING:
return {
{
...state
},
{
...initState
}
}
case FETCH_SUCESS:
return {
...state,
...initState,
data: action.payload,
}
case FETCH_FAILED:
return {
...state,
...initState,
error: action.payload.error,
loading: false
}
default:
return { ...state,
...initState
}
}
}