美好的一天,
我正在使用react-redux和redux-thunk。
下面的示例代码。
projects.jsx
id | x | y | color
1 | 0.3 | 0.4 | 'green'
1 | 0.2 | 0.5 | 'green'
2 | 0.1 | 0.6 | 'black'
2 | 0.9 | 0.1 | 'black'
3 | 0.8 | 0.2 | 'red'
3 | 0.7 | 0.3 | 'red'
/actions/projects.js
const fetch = async () => {
const { data: projects } = await getProjects()
dispatch(storeProjects(projects))
}
const projects = useSelector(state => state.projects)
console.log(projects)
/reducers/index.js
export const storeProjects = (projects) => {
return {
type: 'STORE_PROJECTS',
projects
}
}
问题是
const projects = (state = {}, { type, projects }) => {
switch (type) {
case 'STORE_PROJECTS':
state.projects = projects
return state
default: return state
}
}
export default projects
无法打印项目
以非异步方式进行操作
console.log(projects)
更多详细信息
App.js
const fakeProjects = [ { project: 'fakeProject '}]
dispatch(storeProjects(fakeProjetcs ))
const projects = useSelector(state => state.projects)
console.log(project) // it can now print
}
/reducers/index.js
import { createStore, applyMiddleware } from 'redux'
import { Provider } from 'react-redux'
import ReduxThunk from "redux-thunk"
import reducers from './redux/reducers';
function App() {
const store = createStore(reducers, applyMiddleware(ReduxThunk))
return <>
<Provider store={store}>
//children
</Provider>
</>