我目前正在使用webpack。由于我不理解的原因,我的redux函数不会上传DOM。 但是,Google控制台会返回我的功能的良好结果。
一切看起来都不错,但代码中有一些东西可以创建这个bugg:我的DOM不会渲染我的redux渲染函数。
所以,我已经检查了Webpack配置和index.html数据流,一切看起来都很棒。我有什么遗失的?
这是我的webpack.config.js:
const webpack = require("webpack");
const path = require("path");
module.exports= {
mode: "development",
entry : "./src/index.js",
output: {
path : path.resolve(__dirname, 'dist'),
publicPath: 'dist',
filename : "main.js"
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
//Loaders tell webpack what to do with the entry file
module:{
rules: [{
test: /.(js|jsx)$/,
loader: "babel-loader",
exclude : /node_modules/
}]
},
devServer :{
publicPath: "/",
contentBase: path.join(__dirname, "dist"),
hot: true
}
}
这里是我的index.js:
import {
createPost,
editPost,
setFilter
} from './actions';
import {
appReducer
} from "./reducers.js";
import {
createStore
} from "redux";
let store = createStore(appReducer)
const unsubscribe = store.subscribe(() => {
console.log("state: ", store.getState())
})
store.dispatch(createPost("Brian", "Hello world =D !"));
const root = document.getElementById('root');
const render = () => {
root.innerHTML = ''
const { posts } = store.getState()
posts.forEach((post, index) => {
const item = document.createElement('li')
item.addEventListener('click', () =>
store.dispatch(editPost(index, post.text + '!'))
)
const text = document.createTextNode(post.user + ' - ' + post.text)
item.appendChild(text)
root.appendChild(item)
})
const stopRender = store.subscribe(render)
}
store.dispatch(createPost("user1", "text1"))
store.dispatch(createPost("user2", "text2"))
这里是我的reducer.js:
import {
CREATE_POST,
EDIT_POST,
SET_FILTER
} from "./actionTypes";
import {combineReducers} from "redux";
export function postsReducer(state = [], action) {
switch (action.type) {
case CREATE_POST:
{
const {
type,
...post
} = action
return [...state, post]
}
case EDIT_POST:
{
const {
type,
id,
...newPost
} = action
return state.map((oldPost, index) =>
action.id === index ? { ...oldPost,
...newPost
} : oldPost)
}
default:
return state
}
}
export function filterReducer(state = "all", action) {
if (action.type === SET_FILTER) {
return action.filter
} else {
return state
}
}
export const appReducer = combineReducers({
post : postsReducer,
filter : filterReducer
})
这里是我的index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Learning Redux</title>
</head>
<body>
<div id="root"></div>
<script src="main.js"></script>
</body>
</html>
由于