如何从另一位主管那里重新发布组件



我有一个帖子的ActivityFeed。当我点击ActivityPost组件中的图标时,它会将postId保存在全局状态(EditPostIndex(中,这意味着它的作用类似于活动提要中CreatePostEditPost组件的切换。当我点击editpost图标时,它会显示我想编辑的帖子的正文

活动馈送

const ActivityFeed = () => {
const {posts} = useContext(GlobalContext);
const {editPostIndex} = useContext(GlobalContext);
return (
<div id="mobile-activity">
<DeviceNav />
{ editPostIndex === null ? 
<CreatePost />
:
<EditPost />
}
{posts.slice(0).reverse().map(post => (
<ActivityPost key={post.id} post={post} /> 
))}     
</div>
)
}

ActivityPost

function ActivityPost({post, index}) => {
const {toggleEditPost} = useContext(GlobalContext);
function updatePost(index){
toggleEditPost(index)
}
}

EditPost.js

const EditPost = () => {
const {posts} = useContext(GlobalContext);
const {updatePost} = useContext(GlobalContext);
const {editPostIndex} = useContext(GlobalContext);
let val = posts[editPostIndex].body;
let [body, setBody] = useState(val);
function editPost() {
//update
}
return (
<div  id="make-post">
<div id="create-post">
<textarea value={body} onChange={(e) => setBody(e.target.value)} id="post-activity" placeholder="Tell them what you think."></textarea>
</div>
<div id="create-post-actions">

<button onClick={editPost} id="post">Edit</button>

</div>
</div>
)
}

全局状态/全局上下文

const initialState = {
posts: posts,
editPostIndex: null
}
export const GlobalProvider = ({children}) => {
const [state, dispatch] = useReducer(AppReducer, initialState)
function toggleEditPost(index = null){
dispatch({
type: 'TOGGLE_EDIT_POST',
payload: index
})
//alert(index);
}
function updatePost(post){
dispatch({
type: 'UPDATE_POST',
payload: post
})
toggleEditPost(null);
}
}

问题是,在EditPost组件let val = posts[editPostIndex].body; let [body, setBody] = useState(val);中,useState只渲染一次,因为EditPostIndex已经更改。当我点击编辑帖子图标时,如何使let [body, setBody] = useState(val);更改为我想要编辑的帖子正文?或者重新发送EditPost组件,以便再次设置setBody?

在这种情况下,我认为您需要更多像useState&useEffect检测上下文中的更改EditPost.js.

const [postIndex, setPostIndex] = useState(editPostIndex);
useEffect(() => {
if(editPostIndex !== postIndex){
setPostIndex(editPostIndex);
setBody(posts[editPostIndex].body)
}
}, [setPostIndex, postIndex])

您可以使用redux,它实际上是为此目的而构建的。使用redux,您可以将组件订阅到redux存储,然后推送更新,这将自动更新订阅的组件。

最新更新