So I'm reading through the docs for rtk
, the example shown is after creating a slice with this code:
import { createSlice } from '@reduxjs/toolkit'
const initialState = {
value: 0,
}
export const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
increment: (state) => {
// Redux Toolkit allows us to write "mutating" logic in reducers. It
// doesn't actually mutate the state because it uses the Immer library,
// which detects changes to a "draft state" and produces a brand new
// immutable state based off those changes
state.value += 1
},
decrement: (state) => {
state.value -= 1
},
incrementByAmount: (state, action) => {
state.value += action.payload
},
},
})
// Action creators are generated for each case reducer function
export const { increment, decrement, incrementByAmount } = counterSlice.actions
export default counterSlice.reducer
and then importing the reducer in the store like this :
import { configureStore } from '@reduxjs/toolkit'
import counterReducer from '../features/counter/counterSlice'
export const store = configureStore({
reducer: {
counter: counterReducer,
},
})
But what I'm seeing from the import
is that it's importing counterReducer
although there's no counterReducer
export in the slice file , is that a Redux Toolkit feature or a React feature or a JavaScript feature that I'm not aware of?
It's a "default export" and "default import".
You notice that all exports have a name - except for
export default counterSlice.reducer
In the other file, you can see two different notations:
// has braces - imports the named export `configureStore` from `@reduxjs/toolkit`
import { configureStore } from '@reduxjs/toolkit'
// has no braces - imported the default export from the file `../features/counter/counterSlice` and gives it the name `counterReducer` for this file.
import counterReducer from '../features/counter/counterSlice'
It's an ES Modules feature, so it's a JavaScript thing. When you export something with default
keyword, you can import it with whatever name you want and without {}
. In slice file, there is this export:
export default counterSlice.reducer
And that you can import it with the name you want, they choose to call it counterReducer
:
import counterReducer from '../features/counter/counterSlice'
It's the different between named exports
and default exports
. To know more about it, visit the doc for export statement or JavaScript modules on MDN.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.